query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Gets the body for a license based on a license code
def _get_license_description ( license_code ) : req = requests . get ( "{base_url}/licenses/{license_code}" . format ( base_url = BASE_URL , license_code = license_code ) , headers = _HEADERS ) if req . status_code == requests . codes . ok : s = req . json ( ) [ "body" ] search_curly = re . search ( r'\{(.*)\}' , s ) search_square = re . search ( r'\[(.*)\]' , s ) license = "" replace_string = '{year} {name}' . format ( year = date . today ( ) . year , name = _get_config_name ( ) ) if search_curly : license = re . sub ( r'\{(.+)\}' , replace_string , s ) elif search_square : license = re . sub ( r'\[(.+)\]' , replace_string , s ) else : license = s return license else : print ( Fore . RED + 'No such license. Please check again.' ) , print ( Style . RESET_ALL ) , sys . exit ( )
8,800
https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L70-L94
[ "def", "_FillEventSourceHeap", "(", "self", ",", "storage_writer", ",", "event_source_heap", ",", "start_with_first", "=", "False", ")", ":", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StartTiming", "(", "'fill_event_source_heap'", ")", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StartTiming", "(", "'get_event_source'", ")", "if", "start_with_first", ":", "event_source", "=", "storage_writer", ".", "GetFirstWrittenEventSource", "(", ")", "else", ":", "event_source", "=", "storage_writer", ".", "GetNextWrittenEventSource", "(", ")", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StopTiming", "(", "'get_event_source'", ")", "while", "event_source", ":", "event_source_heap", ".", "PushEventSource", "(", "event_source", ")", "if", "event_source_heap", ".", "IsFull", "(", ")", ":", "break", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StartTiming", "(", "'get_event_source'", ")", "event_source", "=", "storage_writer", ".", "GetNextWrittenEventSource", "(", ")", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StopTiming", "(", "'get_event_source'", ")", "if", "self", ".", "_processing_profiler", ":", "self", ".", "_processing_profiler", ".", "StopTiming", "(", "'fill_event_source_heap'", ")" ]
Gets the license summary and permitted forbidden and required behaviour
def get_license_summary ( license_code ) : try : abs_file = os . path . join ( _ROOT , "summary.json" ) with open ( abs_file , 'r' ) as f : summary_license = json . loads ( f . read ( ) ) [ license_code ] # prints summary print ( Fore . YELLOW + 'SUMMARY' ) print ( Style . RESET_ALL ) , print ( summary_license [ 'summary' ] ) # prints source for summary print ( Style . BRIGHT + 'Source:' ) , print ( Style . RESET_ALL ) , print ( Fore . BLUE + summary_license [ 'source' ] ) print ( Style . RESET_ALL ) # prints cans print ( Fore . GREEN + 'CAN' ) print ( Style . RESET_ALL ) , for rule in summary_license [ 'can' ] : print ( rule ) print ( '' ) # prints cannot print ( Fore . RED + 'CANNOT' ) print ( Style . RESET_ALL ) , for rule in summary_license [ 'cannot' ] : print ( rule ) print ( '' ) # prints musts print ( Fore . BLUE + 'MUST' ) print ( Style . RESET_ALL ) , for rule in summary_license [ 'must' ] : print ( rule ) print ( '' ) except KeyError : print ( Fore . RED + 'No such license. Please check again.' ) , print ( Style . RESET_ALL ) ,
8,801
https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L97-L139
[ "def", "end", "(", "self", ")", ":", "TftpContext", ".", "end", "(", "self", ",", "not", "self", ".", "filelike_fileobj", ")", "self", ".", "metrics", ".", "end_time", "=", "time", ".", "time", "(", ")", "log", ".", "debug", "(", "\"Set metrics.end_time to %s\"", "%", "self", ".", "metrics", ".", "end_time", ")", "self", ".", "metrics", ".", "compute", "(", ")" ]
harvey helps you manage and add license from the command line
def main ( ) : arguments = docopt ( __doc__ , version = __version__ ) if arguments [ 'ls' ] or arguments [ 'list' ] : _get_licences ( ) elif arguments [ '--tldr' ] and arguments [ '<NAME>' ] : get_license_summary ( arguments [ '<NAME>' ] . lower ( ) ) elif arguments [ '--export' ] and arguments [ '<NAME>' ] : save_license ( arguments [ '<NAME>' ] . lower ( ) ) elif arguments [ '<NAME>' ] : print ( _get_license_description ( arguments [ '<NAME>' ] . lower ( ) ) ) else : print ( __doc__ )
8,802
https://github.com/architv/harvey/blob/2b96d57b7a1e0dd706f1f00aba3d92a7ae702960/harvey/harvey.py#L152-L165
[ "def", "blob_data_to_dict", "(", "stat_names", ",", "blobs", ")", ":", "# get the dtypes of each of the stats; we'll just take this from the", "# first iteration and walker", "dtypes", "=", "[", "type", "(", "val", ")", "for", "val", "in", "blobs", "[", "0", "]", "[", "0", "]", "]", "assert", "len", "(", "stat_names", ")", "==", "len", "(", "dtypes", ")", ",", "(", "\"number of stat names must match length of tuples in the blobs\"", ")", "# convert to an array; to ensure that we get the dtypes correct, we'll", "# cast to a structured array", "raw_stats", "=", "numpy", ".", "array", "(", "blobs", ",", "dtype", "=", "zip", "(", "stat_names", ",", "dtypes", ")", ")", "# transpose so that it has shape nwalkers x niterations", "raw_stats", "=", "raw_stats", ".", "transpose", "(", ")", "# now return as a dictionary", "return", "{", "stat", ":", "raw_stats", "[", "stat", "]", "for", "stat", "in", "stat_names", "}" ]
Retrieve the information for a person entity .
def get ( self , user_id ) : path = '/' . join ( [ 'person' , user_id ] ) return self . rachio . get ( path )
8,803
https://github.com/rfverbruggen/rachiopy/blob/c91abc9984f0f453e60fa905285c1b640c3390ae/rachiopy/person.py#L16-L19
[ "def", "_clamp_string", "(", "self", ",", "row_item", ",", "column_index", ",", "delimiter", "=", "''", ")", ":", "width", "=", "(", "self", ".", "_table", ".", "column_widths", "[", "column_index", "]", "-", "self", ".", "_table", ".", "left_padding_widths", "[", "column_index", "]", "-", "self", ".", "_table", ".", "right_padding_widths", "[", "column_index", "]", ")", "if", "termwidth", "(", "row_item", ")", "<=", "width", ":", "return", "row_item", "else", ":", "if", "width", "-", "len", "(", "delimiter", ")", ">=", "0", ":", "clamped_string", "=", "(", "textwrap", "(", "row_item", ",", "width", "-", "len", "(", "delimiter", ")", ")", "[", "0", "]", "+", "delimiter", ")", "else", ":", "clamped_string", "=", "delimiter", "[", ":", "width", "]", "return", "clamped_string" ]
Create empty copy of the current table with copies of all index definitions .
def copy_template ( self , name = None ) : ret = Table ( self . table_name ) ret . _indexes . update ( dict ( ( k , v . copy_template ( ) ) for k , v in self . _indexes . items ( ) ) ) ret ( name ) return ret
8,804
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L632-L639
[ "def", "get_community_badge_progress", "(", "self", ",", "steamID", ",", "badgeID", ",", "format", "=", "None", ")", ":", "parameters", "=", "{", "'steamid'", ":", "steamID", ",", "'badgeid'", ":", "badgeID", "}", "if", "format", "is", "not", "None", ":", "parameters", "[", "'format'", "]", "=", "format", "url", "=", "self", ".", "create_request_url", "(", "self", ".", "interface", ",", "'GetCommunityBadgeProgress'", ",", "1", ",", "parameters", ")", "data", "=", "self", ".", "retrieve_request", "(", "url", ")", "return", "self", ".", "return_data", "(", "data", ",", "format", "=", "format", ")" ]
Create full copy of the current table including table contents and index definitions .
def clone ( self , name = None ) : ret = self . copy_template ( ) . insert_many ( self . obs ) ( name ) return ret
8,805
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L641-L646
[ "def", "from_dict", "(", "cls", ",", "serialized", ")", ":", "if", "serialized", "is", "None", ":", "return", "None", "macaroon", "=", "serialized", ".", "get", "(", "'Macaroon'", ")", "if", "macaroon", "is", "not", "None", ":", "macaroon", "=", "bakery", ".", "Macaroon", ".", "from_dict", "(", "macaroon", ")", "path", "=", "serialized", ".", "get", "(", "'MacaroonPath'", ")", "cookie_name_suffix", "=", "serialized", ".", "get", "(", "'CookieNameSuffix'", ")", "visit_url", "=", "serialized", ".", "get", "(", "'VisitURL'", ")", "wait_url", "=", "serialized", ".", "get", "(", "'WaitURL'", ")", "interaction_methods", "=", "serialized", ".", "get", "(", "'InteractionMethods'", ")", "return", "ErrorInfo", "(", "macaroon", "=", "macaroon", ",", "macaroon_path", "=", "path", ",", "cookie_name_suffix", "=", "cookie_name_suffix", ",", "visit_url", "=", "visit_url", ",", "wait_url", "=", "wait_url", ",", "interaction_methods", "=", "interaction_methods", ")" ]
Deletes an index from the Table . Can be used to drop and rebuild an index or to convert a non - unique index to a unique index or vice versa .
def delete_index ( self , attr ) : if attr in self . _indexes : del self . _indexes [ attr ] self . _uniqueIndexes = [ ind for ind in self . _indexes . values ( ) if ind . is_unique ] return self
8,806
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L689-L698
[ "def", "stop", "(", "self", ")", ":", "self", ".", "__end", ".", "set", "(", ")", "if", "self", ".", "__recv_thread", ":", "self", ".", "__recv_thread", ".", "join", "(", ")", "self", ".", "__recv_thread", "=", "None", "if", "self", ".", "__send_thread", ":", "self", ".", "__send_thread", ".", "join", "(", ")", "self", ".", "__send_thread", "=", "None" ]
Inserts a collection of objects into the table .
def insert_many ( self , it ) : unique_indexes = self . _uniqueIndexes # [ind for ind in self._indexes.values() if ind.is_unique] NO_SUCH_ATTR = object ( ) new_objs = list ( it ) if unique_indexes : for ind in unique_indexes : ind_attr = ind . attr new_keys = dict ( ( getattr ( obj , ind_attr , NO_SUCH_ATTR ) , obj ) for obj in new_objs ) if not ind . accept_none and ( None in new_keys or NO_SUCH_ATTR in new_keys ) : raise KeyError ( "unique key cannot be None or blank for index %s" % ind_attr , [ ob for ob in new_objs if getattr ( ob , ind_attr , NO_SUCH_ATTR ) is None ] ) if len ( new_keys ) < len ( new_objs ) : raise KeyError ( "given sequence contains duplicate keys for index %s" % ind_attr ) for key in new_keys : if key in ind : obj = new_keys [ key ] raise KeyError ( "duplicate unique key value '%s' for index %s" % ( getattr ( obj , ind_attr ) , ind_attr ) , new_keys [ key ] ) for obj in new_objs : self . obs . append ( obj ) for attr , ind in self . _indexes . items ( ) : obval = getattr ( obj , attr ) ind [ obval ] = obj return self
8,807
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L720-L746
[ "def", "stop_experiment", "(", "args", ")", ":", "experiment_id_list", "=", "parse_ids", "(", "args", ")", "if", "experiment_id_list", ":", "experiment_config", "=", "Experiments", "(", ")", "experiment_dict", "=", "experiment_config", ".", "get_all_experiments", "(", ")", "for", "experiment_id", "in", "experiment_id_list", ":", "print_normal", "(", "'Stoping experiment %s'", "%", "experiment_id", ")", "nni_config", "=", "Config", "(", "experiment_dict", "[", "experiment_id", "]", "[", "'fileName'", "]", ")", "rest_port", "=", "nni_config", ".", "get_config", "(", "'restServerPort'", ")", "rest_pid", "=", "nni_config", ".", "get_config", "(", "'restServerPid'", ")", "if", "rest_pid", ":", "kill_command", "(", "rest_pid", ")", "tensorboard_pid_list", "=", "nni_config", ".", "get_config", "(", "'tensorboardPidList'", ")", "if", "tensorboard_pid_list", ":", "for", "tensorboard_pid", "in", "tensorboard_pid_list", ":", "try", ":", "kill_command", "(", "tensorboard_pid", ")", "except", "Exception", "as", "exception", ":", "print_error", "(", "exception", ")", "nni_config", ".", "set_config", "(", "'tensorboardPidList'", ",", "[", "]", ")", "print_normal", "(", "'Stop experiment success!'", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'status'", ",", "'STOPPED'", ")", "time_now", "=", "time", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ",", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'endTime'", ",", "str", "(", "time_now", ")", ")" ]
Removes a collection of objects from the table .
def remove_many ( self , it ) : # find indicies of objects in iterable to_be_deleted = list ( it ) del_indices = [ ] for i , ob in enumerate ( self . obs ) : try : tbd_index = to_be_deleted . index ( ob ) except ValueError : continue else : del_indices . append ( i ) to_be_deleted . pop ( tbd_index ) # quit early if we have found them all if not to_be_deleted : break for i in sorted ( del_indices , reverse = True ) : self . pop ( i ) return self
8,808
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L753-L774
[ "def", "_restart_session", "(", "self", ",", "session", ")", ":", "# remove old session key, if socket is None, that means the", "# session was closed by user and there is no need to restart.", "if", "session", ".", "socket", "is", "not", "None", ":", "self", ".", "log", ".", "info", "(", "\"Attempting restart session for Monitor Id %s.\"", "%", "session", ".", "monitor_id", ")", "del", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "session", ".", "stop", "(", ")", "session", ".", "start", "(", ")", "self", ".", "sessions", "[", "session", ".", "socket", ".", "fileno", "(", ")", "]", "=", "session" ]
Used to order where keys by most selective key first
def _query_attr_sort_fn ( self , attr_val ) : attr , v = attr_val if attr in self . _indexes : idx = self . _indexes [ attr ] if v in idx : return len ( idx [ v ] ) else : return 0 else : return 1e9
8,809
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L776-L786
[ "def", "_xfsdump_output", "(", "data", ")", ":", "out", "=", "{", "}", "summary", "=", "[", "]", "summary_block", "=", "False", "for", "line", "in", "[", "l", ".", "strip", "(", ")", "for", "l", "in", "data", ".", "split", "(", "\"\\n\"", ")", "if", "l", ".", "strip", "(", ")", "]", ":", "line", "=", "re", ".", "sub", "(", "\"^xfsdump: \"", ",", "\"\"", ",", "line", ")", "if", "line", ".", "startswith", "(", "\"session id:\"", ")", ":", "out", "[", "'Session ID'", "]", "=", "line", ".", "split", "(", "\" \"", ")", "[", "-", "1", "]", "elif", "line", ".", "startswith", "(", "\"session label:\"", ")", ":", "out", "[", "'Session label'", "]", "=", "re", ".", "sub", "(", "\"^session label: \"", ",", "\"\"", ",", "line", ")", "elif", "line", ".", "startswith", "(", "\"media file size\"", ")", ":", "out", "[", "'Media size'", "]", "=", "re", ".", "sub", "(", "r\"^media file size\\s+\"", ",", "\"\"", ",", "line", ")", "elif", "line", ".", "startswith", "(", "\"dump complete:\"", ")", ":", "out", "[", "'Dump complete'", "]", "=", "re", ".", "sub", "(", "r\"^dump complete:\\s+\"", ",", "\"\"", ",", "line", ")", "elif", "line", ".", "startswith", "(", "\"Dump Status:\"", ")", ":", "out", "[", "'Status'", "]", "=", "re", ".", "sub", "(", "r\"^Dump Status:\\s+\"", ",", "\"\"", ",", "line", ")", "elif", "line", ".", "startswith", "(", "\"Dump Summary:\"", ")", ":", "summary_block", "=", "True", "continue", "if", "line", ".", "startswith", "(", "\" \"", ")", "and", "summary_block", ":", "summary", ".", "append", "(", "line", ".", "strip", "(", ")", ")", "elif", "not", "line", ".", "startswith", "(", "\" \"", ")", "and", "summary_block", ":", "summary_block", "=", "False", "if", "summary", ":", "out", "[", "'Summary'", "]", "=", "' '", ".", "join", "(", "summary", ")", "return", "out" ]
Deletes matching objects from the table based on given named parameters . If multiple named parameters are given then only objects that satisfy all of the query criteria will be removed .
def delete ( self , * * kwargs ) : if not kwargs : return 0 affected = self . where ( * * kwargs ) self . remove_many ( affected ) return len ( affected )
8,810
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L835-L848
[ "def", "start", "(", "self", ")", ":", "self", ".", "startTime", "=", "time", ".", "time", "(", ")", "self", ".", "configure", "(", "text", "=", "'{0:<d} s'", ".", "format", "(", "0", ")", ")", "self", ".", "update", "(", ")" ]
Sort Table in place using given fields as sort key .
def sort ( self , key , reverse = False ) : if isinstance ( key , ( basestring , list , tuple ) ) : if isinstance ( key , basestring ) : attrdefs = [ s . strip ( ) for s in key . split ( ',' ) ] attr_orders = [ ( a . split ( ) + [ 'asc' , ] ) [ : 2 ] for a in attrdefs ] else : # attr definitions were already resolved to a sequence by the caller if isinstance ( key [ 0 ] , basestring ) : attr_orders = [ ( a . split ( ) + [ 'asc' , ] ) [ : 2 ] for a in key ] else : attr_orders = key attrs = [ attr for attr , order in attr_orders ] # special optimization if all orders are ascending or descending if all ( order == 'asc' for attr , order in attr_orders ) : self . obs . sort ( key = attrgetter ( * attrs ) , reverse = reverse ) elif all ( order == 'desc' for attr , order in attr_orders ) : self . obs . sort ( key = attrgetter ( * attrs ) , reverse = not reverse ) else : # mix of ascending and descending sorts, have to do succession of sorts # leftmost attr is the most primary sort key, so reverse attr_orders to do # succession of sorts from right to left do_all ( self . obs . sort ( key = attrgetter ( attr ) , reverse = ( order == "desc" ) ) for attr , order in reversed ( attr_orders ) ) else : # sorting given a sort key function keyfn = key self . obs . sort ( key = keyfn , reverse = reverse ) return self
8,811
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L857-L895
[ "def", "populate_readme", "(", "revision", ",", "rtd_version", ",", "*", "*", "extra_kwargs", ")", ":", "with", "open", "(", "TEMPLATE_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "img_prefix", "=", "IMG_PREFIX", ".", "format", "(", "revision", "=", "revision", ")", "extra_links", "=", "EXTRA_LINKS", ".", "format", "(", "rtd_version", "=", "rtd_version", ",", "revision", "=", "revision", ")", "docs_img", "=", "DOCS_IMG", ".", "format", "(", "rtd_version", "=", "rtd_version", ")", "bernstein_basis", "=", "BERNSTEIN_BASIS_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "bezier_defn", "=", "BEZIER_DEFN_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "sum_to_unity", "=", "SUM_TO_UNITY_PLAIN", ".", "format", "(", "img_prefix", "=", "img_prefix", ")", "template_kwargs", "=", "{", "\"code_block1\"", ":", "PLAIN_CODE_BLOCK", ",", "\"code_block2\"", ":", "PLAIN_CODE_BLOCK", ",", "\"code_block3\"", ":", "PLAIN_CODE_BLOCK", ",", "\"testcleanup\"", ":", "\"\"", ",", "\"toctree\"", ":", "\"\"", ",", "\"bernstein_basis\"", ":", "bernstein_basis", ",", "\"bezier_defn\"", ":", "bezier_defn", ",", "\"sum_to_unity\"", ":", "sum_to_unity", ",", "\"img_prefix\"", ":", "img_prefix", ",", "\"extra_links\"", ":", "extra_links", ",", "\"docs\"", ":", "\"|docs| \"", ",", "\"docs_img\"", ":", "docs_img", ",", "\"pypi\"", ":", "\"\\n\\n|pypi| \"", ",", "\"pypi_img\"", ":", "PYPI_IMG", ",", "\"versions\"", ":", "\"|versions|\\n\\n\"", ",", "\"versions_img\"", ":", "VERSIONS_IMG", ",", "\"rtd_version\"", ":", "rtd_version", ",", "\"revision\"", ":", "revision", ",", "\"circleci_badge\"", ":", "CIRCLECI_BADGE", ",", "\"circleci_path\"", ":", "\"\"", ",", "\"travis_badge\"", ":", "TRAVIS_BADGE", ",", "\"travis_path\"", ":", "\"\"", ",", "\"appveyor_badge\"", ":", "APPVEYOR_BADGE", ",", "\"appveyor_path\"", ":", "\"\"", ",", "\"coveralls_badge\"", ":", "COVERALLS_BADGE", ",", "\"coveralls_path\"", ":", "COVERALLS_PATH", ",", "\"zenodo\"", ":", "\"|zenodo|\"", ",", "\"zenodo_img\"", ":", "ZENODO_IMG", ",", "\"joss\"", ":", "\" |JOSS|\"", ",", "\"joss_img\"", ":", "JOSS_IMG", ",", "}", "template_kwargs", ".", "update", "(", "*", "*", "extra_kwargs", ")", "readme_contents", "=", "template", ".", "format", "(", "*", "*", "template_kwargs", ")", "# Apply regular expressions to convert Sphinx \"roles\" to plain reST.", "readme_contents", "=", "INLINE_MATH_EXPR", ".", "sub", "(", "inline_math", ",", "readme_contents", ")", "sphinx_modules", "=", "[", "]", "to_replace", "=", "functools", ".", "partial", "(", "mod_replace", ",", "sphinx_modules", "=", "sphinx_modules", ")", "readme_contents", "=", "MOD_EXPR", ".", "sub", "(", "to_replace", ",", "readme_contents", ")", "if", "sphinx_modules", "!=", "[", "\"bezier.curve\"", ",", "\"bezier.surface\"", "]", ":", "raise", "ValueError", "(", "\"Unexpected sphinx_modules\"", ",", "sphinx_modules", ")", "sphinx_docs", "=", "[", "]", "to_replace", "=", "functools", ".", "partial", "(", "doc_replace", ",", "sphinx_docs", "=", "sphinx_docs", ")", "readme_contents", "=", "DOC_EXPR", ".", "sub", "(", "to_replace", ",", "readme_contents", ")", "if", "sphinx_docs", "!=", "[", "\"python/reference/bezier\"", ",", "\"development\"", "]", ":", "raise", "ValueError", "(", "\"Unexpected sphinx_docs\"", ",", "sphinx_docs", ")", "return", "readme_contents" ]
Create a new table containing a subset of attributes with optionally newly - added fields computed from each rec in the original table .
def select ( self , fields , * * exprs ) : fields = self . _parse_fields_string ( fields ) def _make_string_callable ( expr ) : if isinstance ( expr , basestring ) : return lambda r : expr % r else : return expr exprs = dict ( ( k , _make_string_callable ( v ) ) for k , v in exprs . items ( ) ) raw_tuples = [ ] for ob in self . obs : attrvalues = tuple ( getattr ( ob , fieldname , None ) for fieldname in fields ) if exprs : attrvalues += tuple ( expr ( ob ) for expr in exprs . values ( ) ) raw_tuples . append ( attrvalues ) all_names = tuple ( fields ) + tuple ( exprs . keys ( ) ) ret = Table ( ) ret . _indexes . update ( dict ( ( k , v . copy_template ( ) ) for k , v in self . _indexes . items ( ) if k in all_names ) ) return ret ( ) . insert_many ( DataObject ( * * dict ( zip ( all_names , outtuple ) ) ) for outtuple in raw_tuples )
8,812
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L897-L931
[ "def", "shutdown_notebook", "(", "request", ",", "username", ")", ":", "manager", "=", "get_notebook_manager", "(", "request", ")", "if", "manager", ".", "is_running", "(", "username", ")", ":", "manager", ".", "stop_notebook", "(", "username", ")" ]
Create a new table with all string formatted attribute values typically in preparation for formatted output .
def formatted_table ( self , * fields , * * exprs ) : # select_exprs = {} # for f in fields: # select_exprs[f] = lambda r : str(getattr,f,None) fields = set ( fields ) select_exprs = ODict ( ( f , lambda r , f = f : str ( getattr , f , None ) ) for f in fields ) for ename , expr in exprs . items ( ) : if isinstance ( expr , basestring ) : if re . match ( r'^[a-zA-Z_][a-zA-Z0-9_]*$' , expr ) : select_exprs [ ename ] = lambda r : str ( getattr ( r , expr , None ) ) else : if "{}" in expr or "{0}" or "{0:" in expr : select_exprs [ ename ] = lambda r : expr . format ( r ) else : select_exprs [ ename ] = lambda r : expr % getattr ( r , ename , "None" ) return self . select ( * * select_exprs )
8,813
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L933-L958
[ "def", "jacobi_witness", "(", "x", ",", "n", ")", ":", "j", "=", "jacobi", "(", "x", ",", "n", ")", "%", "n", "f", "=", "pow", "(", "x", ",", "n", ">>", "1", ",", "n", ")", "return", "j", "!=", "f" ]
Creates a JoinTerm in preparation for joining with another table to indicate what attribute should be used in the join . Only indexed attributes may be used in a join .
def join_on ( self , attr ) : if attr not in self . _indexes : raise ValueError ( "can only join on indexed attributes" ) return JoinTerm ( self , attr )
8,814
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1075-L1085
[ "def", "make_vbox_dirs", "(", "max_vbox_id", ",", "output_dir", ",", "topology_name", ")", ":", "if", "max_vbox_id", "is", "not", "None", ":", "for", "i", "in", "range", "(", "1", ",", "max_vbox_id", "+", "1", ")", ":", "vbox_dir", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "topology_name", "+", "'-files'", ",", "'vbox'", ",", "'vm-%s'", "%", "i", ")", "os", ".", "makedirs", "(", "vbox_dir", ")" ]
Imports the contents of a CSV - formatted file into this table .
def csv_import ( self , csv_source , encoding = 'utf-8' , transforms = None , row_class = DataObject , * * kwargs ) : reader_args = dict ( ( k , v ) for k , v in kwargs . items ( ) if k not in [ 'encoding' , 'csv_source' , 'transforms' , 'row_class' ] ) reader = lambda src : csv . DictReader ( src , * * reader_args ) return self . _import ( csv_source , encoding , transforms , reader = reader , row_class = row_class )
8,815
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1136-L1161
[ "def", "get_entity_info", "(", "pdb_id", ")", ":", "out", "=", "get_info", "(", "pdb_id", ",", "url_root", "=", "'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='", ")", "out", "=", "to_dict", "(", "out", ")", "return", "remove_at_sign", "(", "out", "[", "'entityInfo'", "]", "[", "'PDB'", "]", ")" ]
Imports the contents of a tab - separated data file into this table .
def tsv_import ( self , xsv_source , encoding = "UTF-8" , transforms = None , row_class = DataObject , * * kwargs ) : return self . _xsv_import ( xsv_source , encoding , transforms = transforms , delimiter = "\t" , row_class = row_class , * * kwargs )
8,816
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1171-L1185
[ "def", "split", "(", "nodeShape", ",", "jobShape", ",", "wallTime", ")", ":", "return", "(", "Shape", "(", "wallTime", ",", "nodeShape", ".", "memory", "-", "jobShape", ".", "memory", ",", "nodeShape", ".", "cores", "-", "jobShape", ".", "cores", ",", "nodeShape", ".", "disk", "-", "jobShape", ".", "disk", ",", "nodeShape", ".", "preemptable", ")", ",", "NodeReservation", "(", "Shape", "(", "nodeShape", ".", "wallTime", "-", "wallTime", ",", "nodeShape", ".", "memory", ",", "nodeShape", ".", "cores", ",", "nodeShape", ".", "disk", ",", "nodeShape", ".", "preemptable", ")", ")", ")" ]
Exports the contents of the table to a CSV - formatted file .
def csv_export ( self , csv_dest , fieldnames = None , encoding = "UTF-8" ) : close_on_exit = False if isinstance ( csv_dest , basestring ) : if PY_3 : csv_dest = open ( csv_dest , 'w' , newline = '' , encoding = encoding ) else : csv_dest = open ( csv_dest , 'wb' ) close_on_exit = True try : if fieldnames is None : fieldnames = list ( _object_attrnames ( self . obs [ 0 ] ) ) if isinstance ( fieldnames , basestring ) : fieldnames = fieldnames . split ( ) csv_dest . write ( ',' . join ( fieldnames ) + NL ) csvout = csv . DictWriter ( csv_dest , fieldnames , extrasaction = 'ignore' , lineterminator = NL ) if hasattr ( self . obs [ 0 ] , "__dict__" ) : csvout . writerows ( o . __dict__ for o in self . obs ) else : do_all ( csvout . writerow ( ODict ( starmap ( lambda obj , fld : ( fld , getattr ( obj , fld ) ) , zip ( repeat ( o ) , fieldnames ) ) ) ) for o in self . obs ) finally : if close_on_exit : csv_dest . close ( )
8,817
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1187-L1222
[ "def", "get_entity_info", "(", "pdb_id", ")", ":", "out", "=", "get_info", "(", "pdb_id", ",", "url_root", "=", "'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='", ")", "out", "=", "to_dict", "(", "out", ")", "return", "remove_at_sign", "(", "out", "[", "'entityInfo'", "]", "[", "'PDB'", "]", ")" ]
Imports the contents of a JSON data file into this table .
def json_import ( self , source , encoding = "UTF-8" , transforms = None , row_class = DataObject ) : class _JsonFileReader ( object ) : def __init__ ( self , src ) : self . source = src def __iter__ ( self ) : current = '' for line in self . source : if current : current += ' ' current += line try : yield json . loads ( current ) current = '' except Exception : pass return self . _import ( source , encoding , transforms = transforms , reader = _JsonFileReader , row_class = row_class )
8,818
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1224-L1252
[ "def", "prox_unity", "(", "X", ",", "step", ",", "axis", "=", "0", ")", ":", "return", "X", "/", "np", ".", "sum", "(", "X", ",", "axis", "=", "axis", ",", "keepdims", "=", "True", ")" ]
Exports the contents of the table to a JSON - formatted file .
def json_export ( self , dest , fieldnames = None , encoding = "UTF-8" ) : close_on_exit = False if isinstance ( dest , basestring ) : if PY_3 : dest = open ( dest , 'w' , encoding = encoding ) else : dest = open ( dest , 'w' ) close_on_exit = True try : if isinstance ( fieldnames , basestring ) : fieldnames = fieldnames . split ( ) if fieldnames is None : do_all ( dest . write ( _to_json ( o ) + '\n' ) for o in self . obs ) else : do_all ( dest . write ( json . dumps ( ODict ( ( f , getattr ( o , f ) ) for f in fieldnames ) ) + '\n' ) for o in self . obs ) finally : if close_on_exit : dest . close ( )
8,819
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1254-L1284
[ "def", "unwatch", "(", "self", ",", "username", ")", ":", "if", "self", ".", "standard_grant_type", "is", "not", "\"authorization_code\"", ":", "raise", "DeviantartError", "(", "\"Authentication through Authorization Code (Grant Type) is required in order to connect to this endpoint.\"", ")", "response", "=", "self", ".", "_req", "(", "'/user/friends/unwatch/{}'", ".", "format", "(", "username", ")", ")", "return", "response", "[", "'success'", "]" ]
Computes a new attribute for each object in table or replaces an existing attribute in each record with a computed value
def add_field ( self , attrname , fn , default = None ) : # for rec in self: def _add_field_to_rec ( rec_ , fn_ = fn , default_ = default ) : try : val = fn_ ( rec_ ) except Exception : val = default_ if isinstance ( rec_ , DataObject ) : rec_ . __dict__ [ attrname ] = val else : setattr ( rec_ , attrname , val ) try : do_all ( _add_field_to_rec ( r ) for r in self ) except AttributeError : raise AttributeError ( "cannot add/modify attribute {!r} in table records" . format ( attrname ) ) return self
8,820
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1286-L1314
[ "def", "handle_subscription_callback", "(", "self", ",", "raw", ",", "verify_token", "=", "model", ".", "Subscription", ".", "VERIFY_TOKEN_DEFAULT", ")", ":", "callback", "=", "model", ".", "SubscriptionCallback", ".", "deserialize", "(", "raw", ")", "callback", ".", "validate", "(", "verify_token", ")", "response_raw", "=", "{", "'hub.challenge'", ":", "callback", ".", "hub_challenge", "}", "return", "response_raw" ]
simple prototype of group by with support for expressions in the group - by clause and outputs
def groupby ( self , keyexpr , * * outexprs ) : if isinstance ( keyexpr , basestring ) : keyattrs = keyexpr . split ( ) keyfn = lambda o : tuple ( getattr ( o , k ) for k in keyattrs ) elif isinstance ( keyexpr , tuple ) : keyattrs = ( keyexpr [ 0 ] , ) keyfn = keyexpr [ 1 ] else : raise TypeError ( "keyexpr must be string or tuple" ) groupedobs = defaultdict ( list ) do_all ( groupedobs [ keyfn ( ob ) ] . append ( ob ) for ob in self . obs ) tbl = Table ( ) do_all ( tbl . create_index ( k , unique = ( len ( keyattrs ) == 1 ) ) for k in keyattrs ) for key , recs in sorted ( groupedobs . items ( ) ) : groupobj = DataObject ( * * dict ( zip ( keyattrs , key ) ) ) do_all ( setattr ( groupobj , subkey , expr ( recs ) ) for subkey , expr in outexprs . items ( ) ) tbl . insert ( groupobj ) return tbl
8,821
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1316-L1347
[ "def", "_sim_texture", "(", "r1", ",", "r2", ")", ":", "return", "sum", "(", "[", "min", "(", "a", ",", "b", ")", "for", "a", ",", "b", "in", "zip", "(", "r1", "[", "\"hist_t\"", "]", ",", "r2", "[", "\"hist_t\"", "]", ")", "]", ")" ]
Create a new table of objects containing no duplicate values .
def unique ( self , key = None ) : if isinstance ( key , basestring ) : key = lambda r , attr = key : getattr ( r , attr , None ) ret = self . copy_template ( ) seen = set ( ) for ob in self : if key is None : try : ob_dict = vars ( ob ) except TypeError : ob_dict = dict ( ( k , getattr ( ob , k ) ) for k in _object_attrnames ( ob ) ) reckey = tuple ( sorted ( ob_dict . items ( ) ) ) else : reckey = key ( ob ) if reckey not in seen : seen . add ( reckey ) ret . insert ( ob ) return ret
8,822
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1349-L1374
[ "def", "stop_experiment", "(", "args", ")", ":", "experiment_id_list", "=", "parse_ids", "(", "args", ")", "if", "experiment_id_list", ":", "experiment_config", "=", "Experiments", "(", ")", "experiment_dict", "=", "experiment_config", ".", "get_all_experiments", "(", ")", "for", "experiment_id", "in", "experiment_id_list", ":", "print_normal", "(", "'Stoping experiment %s'", "%", "experiment_id", ")", "nni_config", "=", "Config", "(", "experiment_dict", "[", "experiment_id", "]", "[", "'fileName'", "]", ")", "rest_port", "=", "nni_config", ".", "get_config", "(", "'restServerPort'", ")", "rest_pid", "=", "nni_config", ".", "get_config", "(", "'restServerPid'", ")", "if", "rest_pid", ":", "kill_command", "(", "rest_pid", ")", "tensorboard_pid_list", "=", "nni_config", ".", "get_config", "(", "'tensorboardPidList'", ")", "if", "tensorboard_pid_list", ":", "for", "tensorboard_pid", "in", "tensorboard_pid_list", ":", "try", ":", "kill_command", "(", "tensorboard_pid", ")", "except", "Exception", "as", "exception", ":", "print_error", "(", "exception", ")", "nni_config", ".", "set_config", "(", "'tensorboardPidList'", ",", "[", "]", ")", "print_normal", "(", "'Stop experiment success!'", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'status'", ",", "'STOPPED'", ")", "time_now", "=", "time", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ",", "time", ".", "localtime", "(", "time", ".", "time", "(", ")", ")", ")", "experiment_config", ".", "update_experiment", "(", "experiment_id", ",", "'endTime'", ",", "str", "(", "time_now", ")", ")" ]
Output the table as a rudimentary HTML table .
def as_html ( self , fields = '*' ) : fields = self . _parse_fields_string ( fields ) def td_value ( v ) : return '<td><div align="{}">{}</div></td>' . format ( ( 'left' , 'right' ) [ isinstance ( v , ( int , float ) ) ] , str ( v ) ) def row_to_tr ( r ) : return "<tr>" + "" . join ( td_value ( getattr ( r , fld ) ) for fld in fields ) + "</tr>\n" ret = "" ret += "<table>\n" ret += "<tr>" + "" . join ( map ( '<th><div align="center">{}</div></th>' . format , fields ) ) + "</tr>\n" ret += "" . join ( map ( row_to_tr , self ) ) ret += "</table>" return ret
8,823
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1450-L1469
[ "def", "_update_beliefs", "(", "self", ",", "sending_clique", ",", "recieving_clique", ",", "operation", ")", ":", "sepset", "=", "frozenset", "(", "sending_clique", ")", ".", "intersection", "(", "frozenset", "(", "recieving_clique", ")", ")", "sepset_key", "=", "frozenset", "(", "(", "sending_clique", ",", "recieving_clique", ")", ")", "# \\sigma_{i \\rightarrow j} = \\sum_{C_i - S_{i, j}} \\beta_i", "# marginalize the clique over the sepset", "sigma", "=", "getattr", "(", "self", ".", "clique_beliefs", "[", "sending_clique", "]", ",", "operation", ")", "(", "list", "(", "frozenset", "(", "sending_clique", ")", "-", "sepset", ")", ",", "inplace", "=", "False", ")", "# \\beta_j = \\beta_j * \\frac{\\sigma_{i \\rightarrow j}}{\\mu_{i, j}}", "self", ".", "clique_beliefs", "[", "recieving_clique", "]", "*=", "(", "sigma", "/", "self", ".", "sepset_beliefs", "[", "sepset_key", "]", "if", "self", ".", "sepset_beliefs", "[", "sepset_key", "]", "else", "sigma", ")", "# \\mu_{i, j} = \\sigma_{i \\rightarrow j}", "self", ".", "sepset_beliefs", "[", "sepset_key", "]", "=", "sigma" ]
Dump out the contents of this table in a nested listing .
def dump ( self , out = sys . stdout , row_fn = repr , limit = - 1 , indent = 0 ) : NL = '\n' if indent : out . write ( " " * indent + self . pivot_key_str ( ) ) else : out . write ( "Pivot: %s" % ',' . join ( self . _pivot_attrs ) ) out . write ( NL ) if self . has_subtables ( ) : do_all ( sub . dump ( out , row_fn , limit , indent + 1 ) for sub in self . subtables if sub ) else : if limit >= 0 : showslice = slice ( 0 , limit ) else : showslice = slice ( None , None ) do_all ( out . write ( " " * ( indent + 1 ) + row_fn ( r ) + NL ) for r in self . obs [ showslice ] ) out . flush ( )
8,824
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1535-L1556
[ "def", "deauthorize_application", "(", "request", ")", ":", "if", "request", ".", "facebook", ":", "user", "=", "User", ".", "objects", ".", "get", "(", "facebook_id", "=", "request", ".", "facebook", ".", "signed_request", ".", "user", ".", "id", ")", "user", ".", "authorized", "=", "False", "user", ".", "save", "(", ")", "return", "HttpResponse", "(", ")", "else", ":", "return", "HttpResponse", "(", "status", "=", "400", ")" ]
Dump out the summary counts of entries in this pivot table as a tabular listing .
def dump_counts ( self , out = sys . stdout , count_fn = len , colwidth = 10 ) : if len ( self . _pivot_attrs ) == 1 : out . write ( "Pivot: %s\n" % ',' . join ( self . _pivot_attrs ) ) maxkeylen = max ( len ( str ( k ) ) for k in self . keys ( ) ) maxvallen = colwidth keytally = { } for k , sub in self . items ( ) : sub_v = count_fn ( sub ) maxvallen = max ( maxvallen , len ( str ( sub_v ) ) ) keytally [ k ] = sub_v for k , sub in self . items ( ) : out . write ( "%-*.*s " % ( maxkeylen , maxkeylen , k ) ) out . write ( "%*s\n" % ( maxvallen , keytally [ k ] ) ) elif len ( self . _pivot_attrs ) == 2 : out . write ( "Pivot: %s\n" % ',' . join ( self . _pivot_attrs ) ) maxkeylen = max ( max ( len ( str ( k ) ) for k in self . keys ( ) ) , 5 ) maxvallen = max ( max ( len ( str ( k ) ) for k in self . subtables [ 0 ] . keys ( ) ) , colwidth ) keytally = dict ( ( k , 0 ) for k in self . subtables [ 0 ] . keys ( ) ) out . write ( "%*s " % ( maxkeylen , '' ) ) out . write ( ' ' . join ( "%*.*s" % ( maxvallen , maxvallen , k ) for k in self . subtables [ 0 ] . keys ( ) ) ) out . write ( ' %*s\n' % ( maxvallen , 'Total' ) ) for k , sub in self . items ( ) : out . write ( "%-*.*s " % ( maxkeylen , maxkeylen , k ) ) for kk , ssub in sub . items ( ) : ssub_v = count_fn ( ssub ) out . write ( "%*d " % ( maxvallen , ssub_v ) ) keytally [ kk ] += ssub_v maxvallen = max ( maxvallen , len ( str ( ssub_v ) ) ) sub_v = count_fn ( sub ) maxvallen = max ( maxvallen , len ( str ( sub_v ) ) ) out . write ( "%*d\n" % ( maxvallen , sub_v ) ) out . write ( '%-*.*s ' % ( maxkeylen , maxkeylen , "Total" ) ) out . write ( ' ' . join ( "%*d" % ( maxvallen , tally ) for k , tally in sorted ( keytally . items ( ) ) ) ) out . write ( " %*d\n" % ( maxvallen , sum ( tally for k , tally in keytally . items ( ) ) ) ) else : raise ValueError ( "can only dump summary counts for 1 or 2-attribute pivots" )
8,825
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1558-L1598
[ "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", ")" ]
Dump out the summary counts of this pivot table as a Table .
def as_table ( self , fn = None , col = None , col_label = None ) : if col_label is None : col_label = col if fn is None : fn = len if col_label is None : col_label = 'count' ret = Table ( ) # topattr = self._pivot_attrs[0] do_all ( ret . create_index ( attr ) for attr in self . _pivot_attrs ) if len ( self . _pivot_attrs ) == 1 : for sub in self . subtables : subattr , subval = sub . _attr_path [ - 1 ] attrdict = { subattr : subval } if col is None or fn is len : attrdict [ col_label ] = fn ( sub ) else : attrdict [ col_label ] = fn ( s [ col ] for s in sub ) ret . insert ( DataObject ( * * attrdict ) ) elif len ( self . _pivot_attrs ) == 2 : for sub in self . subtables : for ssub in sub . subtables : attrdict = dict ( ssub . _attr_path ) if col is None or fn is len : attrdict [ col_label ] = fn ( ssub ) else : attrdict [ col_label ] = fn ( s [ col ] for s in ssub ) ret . insert ( DataObject ( * * attrdict ) ) elif len ( self . _pivot_attrs ) == 3 : for sub in self . subtables : for ssub in sub . subtables : for sssub in ssub . subtables : attrdict = dict ( sssub . _attr_path ) if col is None or fn is len : attrdict [ col_label ] = fn ( sssub ) else : attrdict [ col_label ] = fn ( s [ col ] for s in sssub ) ret . insert ( DataObject ( * * attrdict ) ) else : raise ValueError ( "can only dump summary counts for 1 or 2-attribute pivots" ) return ret
8,826
https://github.com/ptmcg/littletable/blob/8352f7716e458e55a6997372dadf92e179d19f98/littletable.py#L1600-L1642
[ "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", ")" ]
Collates values needed by LOG_FORMAT
def _update_record ( record ) : # Standard fields dt = datetime . fromtimestamp ( record . created ) # Truncate microseconds to milliseconds record . springtime = str ( dt ) [ : - 3 ] record . levelname_spring = "WARN" if record . levelname == "WARNING" else record . levelname record . process_id = str ( os . getpid ( ) ) record . thread_name = ( current_thread ( ) . getName ( ) ) [ : 15 ] record . logger_name = record . name [ : 40 ] record . tracing_information = "" # Optional distributed tracing information tracing_information = _tracing_information ( ) if tracing_information : record . tracing_information = "[" + "," . join ( tracing_information ) + "] "
8,827
https://github.com/davidcarboni/Flask-Sleuth/blob/2191aa2a929ec43c0176ec51c7abef924b12d015/sleuth/__init__.py#L41-L68
[ "def", "expired", "(", "self", ")", ":", "if", "self", ".", "_expired_latch", ":", "return", "True", "self", ".", "_check_time_backwards", "(", ")", "if", "time", ".", "time", "(", ")", ">", "self", ".", "end", ":", "self", ".", "_expired_latch", "=", "True", "return", "True", "return", "False" ]
Gets B3 distributed tracing information if available . This is returned as a list ready to be formatted into Spring Cloud Sleuth compatible format .
def _tracing_information ( ) : # We'll collate trace information if the B3 headers have been collected: values = b3 . values ( ) if values [ b3 . b3_trace_id ] : # Trace information would normally be sent to Zipkin if either of sampled or debug ("flags") is set to 1 # However we're not currently using Zipkin, so it's always false # exported = "true" if values[b3.b3_sampled] == '1' or values[b3.b3_flags] == '1' else "false" return [ current_app . name if current_app . name else " - " , values [ b3 . b3_trace_id ] , values [ b3 . b3_span_id ] , "false" , ]
8,828
https://github.com/davidcarboni/Flask-Sleuth/blob/2191aa2a929ec43c0176ec51c7abef924b12d015/sleuth/__init__.py#L71-L88
[ "async", "def", "incoming", "(", "self", ")", ":", "msg", "=", "await", "self", ".", "_queue", ".", "get", "(", ")", "self", ".", "_queue", ".", "task_done", "(", ")", "return", "msg" ]
Authenticates to the api and sets up client information .
def _authenticate ( self ) : data = { 'username' : self . username , 'password' : self . password } url = '{base}/client/login' . format ( base = self . base_url ) response = self . _session . get ( url , params = data ) print ( response . text ) data = response . json ( ) if not data . get ( 'success' ) : raise InvalidCredentials ( data . get ( 'reason' , None ) ) self . _populate_info ( data )
8,829
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L75-L85
[ "def", "get", "(", "self", ",", "id", "=", "None", ",", "name", "=", "None", ")", ":", "# Validate arguments - use an xor", "if", "not", "(", "id", "is", "None", ")", "^", "(", "name", "is", "None", ")", ":", "raise", "ValueError", "(", "\"Either id or name must be set (but not both!)\"", ")", "# If it's just ID provided, call the parent function", "if", "id", "is", "not", "None", ":", "return", "super", "(", "TaskQueueManager", ",", "self", ")", ".", "get", "(", "id", "=", "id", ")", "# Try getting the task queue by name", "return", "self", ".", "list", "(", "filters", "=", "{", "\"name\"", ":", "name", "}", ")", "[", "0", "]" ]
Log out of the API .
def _logout ( self , reset = True ) : url = '{base}/client/auth/logout' . format ( base = self . base_url ) response = self . _session . get ( url , params = self . _parameters ) if response . ok : if reset : self . _reset ( ) return True else : return False
8,830
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L127-L136
[ "def", "merge_csv_metadata", "(", "d", ",", "csvs", ")", ":", "logger_csvs", ".", "info", "(", "\"enter merge_csv_metadata\"", ")", "# Add CSV to paleoData", "if", "\"paleoData\"", "in", "d", ":", "d", "[", "\"paleoData\"", "]", "=", "_merge_csv_section", "(", "d", "[", "\"paleoData\"", "]", ",", "\"paleo\"", ",", "csvs", ")", "# Add CSV to chronData", "if", "\"chronData\"", "in", "d", ":", "d", "[", "\"chronData\"", "]", "=", "_merge_csv_section", "(", "d", "[", "\"chronData\"", "]", ",", "\"chron\"", ",", "csvs", ")", "logger_csvs", ".", "info", "(", "\"exit merge_csv_metadata\"", ")", "return", "d" ]
The internal state of the object .
def _state ( self ) : state = { } required_keys = ( 'deviceStatusInfo' , 'gasUsage' , 'powerUsage' , 'thermostatInfo' , 'thermostatStates' ) try : for _ in range ( self . _state_retries ) : state . update ( self . _get_data ( '/client/auth/retrieveToonState' ) ) except TypeError : self . _logger . exception ( 'Could not get answer from service.' ) message = ( 'Updating internal state with retrieved ' 'state:{state}' ) . format ( state = state ) self . _logger . debug ( message ) self . _state_ . update ( state ) if not all ( [ key in self . _state_ . keys ( ) for key in required_keys ] ) : raise IncompleteResponse ( state ) return self . _state_
8,831
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L162-L188
[ "def", "unbind", "(", "self", ",", "devices_to_unbind", ")", ":", "if", "self", ".", "entity_api_key", "==", "\"\"", ":", "return", "{", "'status'", ":", "'failure'", ",", "'response'", ":", "'No API key found in request'", "}", "url", "=", "self", ".", "base_url", "+", "\"api/0.1.0/subscribe/unbind\"", "headers", "=", "{", "\"apikey\"", ":", "self", ".", "entity_api_key", "}", "data", "=", "{", "\"exchange\"", ":", "\"amq.topic\"", ",", "\"keys\"", ":", "devices_to_unbind", ",", "\"queue\"", ":", "self", ".", "entity_id", "}", "with", "self", ".", "no_ssl_verification", "(", ")", ":", "r", "=", "requests", ".", "delete", "(", "url", ",", "json", "=", "data", ",", "headers", "=", "headers", ")", "print", "(", "r", ")", "response", "=", "dict", "(", ")", "if", "\"No API key\"", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "json", ".", "loads", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", "[", "'message'", "]", "elif", "'unbind'", "in", "str", "(", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", ")", ":", "response", "[", "\"status\"", "]", "=", "\"success\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "else", ":", "response", "[", "\"status\"", "]", "=", "\"failure\"", "r", "=", "r", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "response", "[", "\"response\"", "]", "=", "str", "(", "r", ")", "return", "response" ]
Retrieves a smokedetector object by its name
def get_smokedetector_by_name ( self , name ) : return next ( ( smokedetector for smokedetector in self . smokedetectors if smokedetector . name . lower ( ) == name . lower ( ) ) , None )
8,832
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L236-L243
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Retrieves a light object by its name
def get_light_by_name ( self , name ) : return next ( ( light for light in self . lights if light . name . lower ( ) == name . lower ( ) ) , None )
8,833
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L253-L260
[ "def", "handleServerEvents", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "'MSG %s'", ",", "msg", ")", "self", ".", "handleConnectionState", "(", "msg", ")", "if", "msg", ".", "typeName", "==", "\"error\"", ":", "self", ".", "handleErrorEvents", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_CURRENT_TIME\"", "]", ":", "if", "self", ".", "time", "<", "msg", ".", "time", ":", "self", ".", "time", "=", "msg", ".", "time", "elif", "(", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_MKT_DEPTH\"", "]", "or", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_MKT_DEPTH_L2\"", "]", ")", ":", "self", ".", "handleMarketDepth", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_TICK_STRING\"", "]", ":", "self", ".", "handleTickString", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_TICK_PRICE\"", "]", ":", "self", ".", "handleTickPrice", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_TICK_GENERIC\"", "]", ":", "self", ".", "handleTickGeneric", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_TICK_SIZE\"", "]", ":", "self", ".", "handleTickSize", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_TICK_OPTION\"", "]", ":", "self", ".", "handleTickOptionComputation", "(", "msg", ")", "elif", "(", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_OPEN_ORDER\"", "]", "or", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_OPEN_ORDER_END\"", "]", "or", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_ORDER_STATUS\"", "]", ")", ":", "self", ".", "handleOrders", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_HISTORICAL_DATA\"", "]", ":", "self", ".", "handleHistoricalData", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_ACCOUNT_UPDATES\"", "]", ":", "self", ".", "handleAccount", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_PORTFOLIO_UPDATES\"", "]", ":", "self", ".", "handlePortfolio", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_POSITION\"", "]", ":", "self", ".", "handlePosition", "(", "msg", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TYPE_NEXT_ORDER_ID\"", "]", ":", "self", ".", "handleNextValidId", "(", "msg", ".", "orderId", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_CONNECTION_CLOSED\"", "]", ":", "self", ".", "handleConnectionClosed", "(", "msg", ")", "# elif msg.typeName == dataTypes[\"MSG_TYPE_MANAGED_ACCOUNTS\"]:", "# self.accountCode = msg.accountsList", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_COMMISSION_REPORT\"", "]", ":", "self", ".", "commission", "=", "msg", ".", "commissionReport", ".", "m_commission", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_CONTRACT_DETAILS\"", "]", ":", "self", ".", "handleContractDetails", "(", "msg", ",", "end", "=", "False", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_CONTRACT_DETAILS_END\"", "]", ":", "self", ".", "handleContractDetails", "(", "msg", ",", "end", "=", "True", ")", "elif", "msg", ".", "typeName", "==", "dataTypes", "[", "\"MSG_TICK_SNAPSHOT_END\"", "]", ":", "self", ".", "ibCallback", "(", "caller", "=", "\"handleTickSnapshotEnd\"", ",", "msg", "=", "msg", ")", "else", ":", "# log handler msg", "self", ".", "log_msg", "(", "\"server\"", ",", "msg", ")" ]
Retrieves a smartplug object by its name
def get_smartplug_by_name ( self , name ) : return next ( ( plug for plug in self . smartplugs if plug . name . lower ( ) == name . lower ( ) ) , None )
8,834
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L270-L277
[ "def", "run_all", "(", ")", ":", "DATA_DIR", "=", "\"/home/annaho/TheCannon/code/apogee_lamost/xcalib_4labels\"", "dates", "=", "os", ".", "listdir", "(", "\"/home/share/LAMOST/DR2/DR2_release\"", ")", "dates", "=", "np", ".", "array", "(", "dates", ")", "dates", "=", "np", ".", "delete", "(", "dates", ",", "np", ".", "where", "(", "dates", "==", "'.directory'", ")", "[", "0", "]", "[", "0", "]", ")", "dates", "=", "np", ".", "delete", "(", "dates", ",", "np", ".", "where", "(", "dates", "==", "'all_folders.list'", ")", "[", "0", "]", "[", "0", "]", ")", "dates", "=", "np", ".", "delete", "(", "dates", ",", "np", ".", "where", "(", "dates", "==", "'dr2.lis'", ")", "[", "0", "]", "[", "0", "]", ")", "for", "date", "in", "dates", ":", "if", "glob", ".", "glob", "(", "\"*%s*.txt\"", "%", "date", ")", ":", "print", "(", "\"%s done\"", "%", "date", ")", "else", ":", "print", "(", "\"running %s\"", "%", "date", ")", "run_one_date", "(", "date", ")" ]
Retrieves a thermostat state object by its assigned name
def get_thermostat_state_by_name ( self , name ) : self . _validate_thermostat_state_name ( name ) return next ( ( state for state in self . thermostat_states if state . name . lower ( ) == name . lower ( ) ) , None )
8,835
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L347-L355
[ "def", "OnRootView", "(", "self", ",", "event", ")", ":", "self", ".", "adapter", ",", "tree", ",", "rows", "=", "self", ".", "RootNode", "(", ")", "self", ".", "squareMap", ".", "SetModel", "(", "tree", ",", "self", ".", "adapter", ")", "self", ".", "RecordHistory", "(", ")", "self", ".", "ConfigureViewTypeChoices", "(", ")" ]
Retrieves a thermostat state object by its id
def get_thermostat_state_by_id ( self , id_ ) : return next ( ( state for state in self . thermostat_states if state . id == id_ ) , None )
8,836
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L357-L364
[ "def", "OnRootView", "(", "self", ",", "event", ")", ":", "self", ".", "adapter", ",", "tree", ",", "rows", "=", "self", ".", "RootNode", "(", ")", "self", ".", "squareMap", ".", "SetModel", "(", "tree", ",", "self", ".", "adapter", ")", "self", ".", "RecordHistory", "(", ")", "self", ".", "ConfigureViewTypeChoices", "(", ")" ]
The state of the thermostat programming
def thermostat_state ( self ) : current_state = self . thermostat_info . active_state state = self . get_thermostat_state_by_id ( current_state ) if not state : self . _logger . debug ( 'Manually set temperature, no Thermostat ' 'State chosen!' ) return state
8,837
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L377-L387
[ "def", "_init_nt_hdr", "(", "self", ",", "line", ")", ":", "line", "=", "line", ".", "replace", "(", "'.'", ",", "'_'", ")", "line", "=", "line", ".", "replace", "(", "' '", ",", "'_'", ")", "line", "=", "line", ".", "replace", "(", "'#'", ",", "'N'", ")", "line", "=", "line", ".", "replace", "(", "'-'", ",", "'_'", ")", "line", "=", "line", ".", "replace", "(", "'\"'", ",", "''", ")", "#line = re.sub(r\"_$\", r\"\", line)", "hdrs", "=", "re", ".", "split", "(", "self", ".", "sep", ",", "line", ")", "if", "''", "in", "hdrs", ":", "hdrs", "=", "NCBIgeneFileReader", ".", "replace_nulls", "(", "hdrs", ")", "# Init indexes which will be converted to int or float", "self", ".", "idxs_int", "=", "[", "idx", "for", "idx", ",", "hdr", "in", "enumerate", "(", "hdrs", ")", "if", "hdr", "in", "self", ".", "int_hdrs", "]", "self", ".", "idxs_float", "=", "[", "idx", "for", "idx", ",", "hdr", "in", "enumerate", "(", "hdrs", ")", "if", "hdr", "in", "self", ".", "float_hdrs", "]", "assert", "hdrs", "[", "6", "]", "==", "'Aliases'", "return", "namedtuple", "(", "'ntncbi'", ",", "' '", ".", "join", "(", "hdrs", ")", ")" ]
Changes the thermostat state to the one passed as an argument as name
def thermostat_state ( self , name ) : self . _validate_thermostat_state_name ( name ) id_ = next ( ( key for key in STATES . keys ( ) if STATES [ key ] . lower ( ) == name . lower ( ) ) , None ) data = copy . copy ( self . _parameters ) data . update ( { 'state' : 2 , 'temperatureState' : id_ } ) response = self . _get_data ( '/client/auth/schemeState' , data ) self . _logger . debug ( 'Response received {}' . format ( response ) ) self . _clear_cache ( )
8,838
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L390-L403
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
A temperature to set the thermostat to . Requires a float .
def thermostat ( self , temperature ) : target = int ( temperature * 100 ) data = copy . copy ( self . _parameters ) data . update ( { 'value' : target } ) response = self . _get_data ( '/client/auth/setPoint' , data ) self . _logger . debug ( 'Response received {}' . format ( response ) ) self . _clear_cache ( )
8,839
https://github.com/costastf/toonlib/blob/2fa95430240d1a1c2a85a8827aecfcb1ca41c18c/toonlib/toonlib.py#L415-L425
[ "def", "register_on_snapshot_deleted", "(", "self", ",", "callback", ")", ":", "event_type", "=", "library", ".", "VBoxEventType", ".", "on_snapshot_deleted", "return", "self", ".", "event_source", ".", "register_callback", "(", "callback", ",", "event_type", ")" ]
adaptation of networkx dfs
def euler_tour_dfs ( G , source = None ) : if source is None : # produce edges for all components nodes = G else : # produce edges for components with source nodes = [ source ] yielder = [ ] visited = set ( ) for start in nodes : if start in visited : continue visited . add ( start ) stack = [ ( start , iter ( G [ start ] ) ) ] while stack : parent , children = stack [ - 1 ] try : child = next ( children ) if child not in visited : # yielder += [[parent, child]] yielder += [ parent ] visited . add ( child ) stack . append ( ( child , iter ( G [ child ] ) ) ) except StopIteration : if stack : last = stack [ - 1 ] yielder += [ last [ 0 ] ] stack . pop ( ) return yielder
8,840
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/dynamic_connectivity.py#L12-L41
[ "def", "touch_object", "(", "self", ",", "objects", ":", "Set", "[", "Object", "]", ")", "->", "Set", "[", "Object", "]", ":", "objects_per_box", "=", "self", ".", "_separate_objects_by_boxes", "(", "objects", ")", "return_set", "=", "set", "(", ")", "for", "box", ",", "box_objects", "in", "objects_per_box", ".", "items", "(", ")", ":", "candidate_objects", "=", "box", ".", "objects", "for", "object_", "in", "box_objects", ":", "for", "candidate_object", "in", "candidate_objects", ":", "if", "self", ".", "_objects_touch_each_other", "(", "object_", ",", "candidate_object", ")", ":", "return_set", ".", "add", "(", "candidate_object", ")", "return", "return_set" ]
s = 3 s = B
def reroot ( self , s ) : # Splice out the first part of the sequence ending with the occurrence before os # remove its first occurrence (or), o_s1 = self . first_lookup [ s ] splice1 = self . tour [ 1 : o_s1 ] rest = self . tour [ o_s1 + 1 : ] new_tour = [ s ] + rest + splice1 + [ s ] new_tree = TestETT . from_tour ( new_tour , fast = self . fast ) return new_tree
8,841
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/dynamic_connectivity.py#L521-L539
[ "def", "parse_registries", "(", "filesystem", ",", "registries", ")", ":", "results", "=", "{", "}", "for", "path", "in", "registries", ":", "with", "NamedTemporaryFile", "(", "buffering", "=", "0", ")", "as", "tempfile", ":", "filesystem", ".", "download", "(", "path", ",", "tempfile", ".", "name", ")", "registry", "=", "RegistryHive", "(", "tempfile", ".", "name", ")", "registry", ".", "rootkey", "=", "registry_root", "(", "path", ")", "results", ".", "update", "(", "{", "k", ".", "path", ":", "(", "k", ".", "timestamp", ",", "k", ".", "values", ")", "for", "k", "in", "registry", ".", "keys", "(", ")", "}", ")", "return", "results" ]
Using notation where 0 is top level
def remove_edge ( self , u , v ) : # Remove (u, v) from represented graph print ( 'Dynamically removing uv=(%r, %r)' % ( u , v ) ) self . graph . remove_edge ( u , v ) e = ( u , v ) # Remove edge e = (u, v) from all graphs. if not self . forests [ 0 ] . has_edge ( u , v ) : # If (u, v) is a non-tree edge, simply delete it. # Nothing else to do. return # If (u, v) is a tree edge we delete it and search for a replacement. # Delete from all higher levels for i in reversed ( range ( 0 , self . level [ e ] + 1 ) ) : self . forests [ i ] . remove_edge ( u , v ) # Determine if another edge that connects u and v exists. # (This must be an edge r, level[r] <= level[e]) # (Find max possible level[r] <= level[e]) for i in reversed ( range ( 0 , self . level [ e ] + 1 ) ) : # Tu != Tw b/c (u, v) was just deleted from all forests Tu = self . forests [ i ] . subtree ( u ) print ( 'Tu = %r' % ( list ( Tu . nodes ( ) ) , ) ) Tv = self . forests [ i ] . subtree ( v ) print ( 'Tv = %r' % ( list ( Tv . nodes ( ) ) , ) ) # Relabel so len(Tu) <= len(Tv) # This ensures len(Tu) < 2 ** (floor(log(n)) - i) if len ( Tu ) > len ( Tv ) : Tu , Tv = Tv , Tu # Note len(Tu) <= 2 * (len(Tu) + len(Tv) + 1) # We can afford to push all of Tu's edges to the next level and # still preserve invariant 1. seen_ = set ( [ ] ) for x in Tu . nodes ( ) : # Visit all edges INCIDENT (in real graph) to nodes in Tu. # This lets us find non-tree edges to make a tree edge seen_ . add ( x ) for y in self . graph . neighbors ( x ) : if y in seen_ : continue # print('Check replacement edge xy=(%r, %r)' % (x, y)) if y in Tv : print ( '* Found replacement xy=(%r, %r)' % ( x , y ) ) # edge (x, y) is a replacement edge. # add (x, y) to prev forests F[0:i+1] # This is the only place edges are added to forets of # higher levels. if len ( self . forests ) == i + 1 : self . forests . append ( DummyEulerTourForest ( self . graph . nodes ( ) ) ) for j in range ( 0 , i + 2 ) : print ( '* Add replacment to F[j=%r]' % ( j , ) ) # Need euler tree augmentation for outgoing level edges self . forests [ j ] . add_edge ( x , y ) return else : print ( '* Charging xy=(%r, %r)' % ( x , y ) ) # charge --- add (x, y) to next level # this pays for our search in an amortized sense # (ie, the next search at this level wont consider this) if len ( self . forests ) == i + 1 : self . forests . append ( DummyEulerTourForest ( self . graph . nodes ( ) ) ) if self . forests [ i ] . has_edge ( x , y ) : self . forests [ i + 1 ] . add_edge ( x , y ) # # assert False, 'we got it, should add it?' self . level [ ( x , y ) ] = i + 1
8,842
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/experimental/dynamic_connectivity.py#L853-L923
[ "def", "add_json_mask", "(", "self", ",", "start", ",", "method_str", ",", "json_producer", ")", ":", "def", "send_json", "(", "drh", ",", "rem_path", ")", ":", "obj", "=", "json_producer", "(", "drh", ",", "rem_path", ")", "if", "not", "isinstance", "(", "obj", ",", "Response", ")", ":", "obj", "=", "Response", "(", "obj", ")", "ctype", "=", "obj", ".", "get_ctype", "(", "\"application/json\"", ")", "code", "=", "obj", ".", "code", "obj", "=", "obj", ".", "response", "if", "obj", "is", "None", ":", "drh", ".", "send_error", "(", "404", ",", "\"File not found\"", ")", "return", "None", "f", "=", "BytesIO", "(", ")", "json_str", "=", "json_dumps", "(", "obj", ")", "if", "isinstance", "(", "json_str", ",", "(", "str", ",", "unicode", ")", ")", ":", "try", ":", "json_str", "=", "json_str", ".", "decode", "(", "'utf8'", ")", "except", "AttributeError", ":", "pass", "json_str", "=", "json_str", ".", "encode", "(", "'utf8'", ")", "f", ".", "write", "(", "json_str", ")", "f", ".", "flush", "(", ")", "size", "=", "f", ".", "tell", "(", ")", "f", ".", "seek", "(", "0", ")", "# handle ETag caching", "if", "drh", ".", "request_version", ">=", "\"HTTP/1.1\"", ":", "e_tag", "=", "\"{0:x}\"", ".", "format", "(", "zlib", ".", "crc32", "(", "f", ".", "read", "(", ")", ")", "&", "0xFFFFFFFF", ")", "f", ".", "seek", "(", "0", ")", "match", "=", "_getheader", "(", "drh", ".", "headers", ",", "'if-none-match'", ")", "if", "match", "is", "not", "None", ":", "if", "drh", ".", "check_cache", "(", "e_tag", ",", "match", ")", ":", "f", ".", "close", "(", ")", "return", "None", "drh", ".", "send_header", "(", "\"ETag\"", ",", "e_tag", ",", "end_header", "=", "True", ")", "drh", ".", "send_header", "(", "\"Cache-Control\"", ",", "\"max-age={0}\"", ".", "format", "(", "self", ".", "max_age", ")", ",", "end_header", "=", "True", ")", "drh", ".", "send_response", "(", "code", ")", "drh", ".", "send_header", "(", "\"Content-Type\"", ",", "ctype", ")", "drh", ".", "send_header", "(", "\"Content-Length\"", ",", "size", ")", "drh", ".", "end_headers", "(", ")", "return", "f", "self", ".", "_add_file_mask", "(", "start", ",", "method_str", ",", "send_json", ")" ]
also preprocesses flags
def extend_regex2 ( regexpr , reflags = 0 ) : regexpr = extend_regex ( regexpr ) IGNORE_CASE_PREF = '\\c' if regexpr . startswith ( IGNORE_CASE_PREF ) : # hack for vim-like ignore case regexpr = regexpr [ len ( IGNORE_CASE_PREF ) : ] reflags = reflags | re . IGNORECASE return regexpr , reflags
8,843
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_regex.py#L91-L101
[ "def", "_getshapes_2d", "(", "center", ",", "max_radius", ",", "shape", ")", ":", "index_mean", "=", "shape", "*", "center", "index_radius", "=", "max_radius", "/", "2.0", "*", "np", ".", "array", "(", "shape", ")", "# Avoid negative indices", "min_idx", "=", "np", ".", "maximum", "(", "np", ".", "floor", "(", "index_mean", "-", "index_radius", ")", ",", "0", ")", ".", "astype", "(", "int", ")", "max_idx", "=", "np", ".", "ceil", "(", "index_mean", "+", "index_radius", ")", ".", "astype", "(", "int", ")", "idx", "=", "[", "slice", "(", "minx", ",", "maxx", ")", "for", "minx", ",", "maxx", "in", "zip", "(", "min_idx", ",", "max_idx", ")", "]", "shapes", "=", "[", "(", "idx", "[", "0", "]", ",", "slice", "(", "None", ")", ")", ",", "(", "slice", "(", "None", ")", ",", "idx", "[", "1", "]", ")", "]", "return", "tuple", "(", "idx", ")", ",", "tuple", "(", "shapes", ")" ]
Creates a named regex group that can be referend via a backref . If key is None the backref is referenced by number .
def named_field ( key , regex , vim = False ) : if key is None : #return regex return r'(%s)' % ( regex , ) if vim : return r'\(%s\)' % ( regex ) else : return r'(?P<%s>%s)' % ( key , regex )
8,844
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_regex.py#L124-L138
[ "def", "pause", "(", "self", ")", "->", "None", ":", "with", "self", ".", "__state_lock", ":", "if", "self", ".", "__state", "==", "DataChannelBuffer", ".", "State", ".", "started", ":", "self", ".", "__state", "=", "DataChannelBuffer", ".", "State", ".", "paused" ]
r thin wrapper around re . sub regex_replace
def regex_replace ( regex , repl , text ) : return re . sub ( regex , repl , text , * * RE_KWARGS )
8,845
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_regex.py#L203-L243
[ "def", "ReadConflicts", "(", "self", ",", "collection_link", ",", "feed_options", "=", "None", ")", ":", "if", "feed_options", "is", "None", ":", "feed_options", "=", "{", "}", "return", "self", ".", "QueryConflicts", "(", "collection_link", ",", "None", ",", "feed_options", ")" ]
Clear loady s cache .
def clear ( prompt = True , cache = None ) : cache = cache or config . cache ( ) if prompt : answer = input ( 'Clear library cache files in %s/? (yN) ' % cache ) if not answer . startswith ( 'y' ) : return False shutil . rmtree ( cache , ignore_errors = True ) return True
8,846
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/library.py#L10-L19
[ "def", "_wavefunction", "(", "self", ",", "quil_program", ",", "random_seed", ")", "->", "Wavefunction", ":", "payload", "=", "wavefunction_payload", "(", "quil_program", ",", "random_seed", ")", "response", "=", "post_json", "(", "self", ".", "session", ",", "self", ".", "sync_endpoint", "+", "\"/qvm\"", ",", "payload", ")", "return", "Wavefunction", ".", "from_bit_packed_string", "(", "response", ".", "content", ")" ]
Create a Library from a git path .
def create ( gitpath , cache = None ) : if gitpath . startswith ( config . LIBRARY_PREFIX ) : path = gitpath [ len ( config . LIBRARY_PREFIX ) : ] return Library ( * path . split ( '/' ) , cache = cache )
8,847
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/library.py#L67-L74
[ "def", "send_event", "(", "self", ",", "event_type", ",", "category", "=", "None", ",", "dimensions", "=", "None", ",", "properties", "=", "None", ",", "timestamp", "=", "None", ")", ":", "if", "category", "and", "category", "not", "in", "SUPPORTED_EVENT_CATEGORIES", ":", "raise", "ValueError", "(", "'Event category is not one of the supported'", "+", "'types: {'", "+", "', '", ".", "join", "(", "SUPPORTED_EVENT_CATEGORIES", ")", "+", "'}'", ")", "data", "=", "{", "'eventType'", ":", "event_type", ",", "'category'", ":", "category", ",", "'dimensions'", ":", "dimensions", "or", "{", "}", ",", "'properties'", ":", "properties", "or", "{", "}", ",", "'timestamp'", ":", "int", "(", "timestamp", ")", "if", "timestamp", "else", "None", ",", "}", "_logger", ".", "debug", "(", "'Sending event to SignalFx: %s'", ",", "data", ")", "self", ".", "_add_extra_dimensions", "(", "data", ")", "return", "self", ".", "_send_event", "(", "event_data", "=", "data", ",", "url", "=", "'{0}/{1}'", ".", "format", "(", "self", ".", "_endpoint", ",", "self", ".", "_INGEST_ENDPOINT_EVENT_SUFFIX", ")", ",", "session", "=", "self", ".", "_session", ")" ]
Load the library .
def load ( self ) : if not git : raise EnvironmentError ( MISSING_GIT_ERROR ) if os . path . exists ( self . path ) : if not config . CACHE_DISABLE : return shutil . rmtree ( self . path , ignore_errors = True ) with files . remove_on_exception ( self . path ) : url = self . GIT_URL . format ( * * vars ( self ) ) repo = git . Repo . clone_from ( url = url , to_path = self . path , b = self . branch ) if self . commit : repo . head . reset ( self . commit , index = True , working_tree = True )
8,848
https://github.com/timedata-org/loady/blob/94ffcdb92f15a28f3c85f77bd293a9cb59de4cad/loady/library.py#L49-L64
[ "def", "_build_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Search you Azure AD contacts from mutt or the command-line.'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--config'", ",", "help", "=", "'Specify alternative configuration file.'", ",", "metavar", "=", "\"FILE\"", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "dest", "=", "\"log_level\"", ",", "action", "=", "'store_const'", ",", "const", "=", "logging", ".", "INFO", ",", "help", "=", "'Be verbose about what is going on (stderr).'", ")", "parser", ".", "add_argument", "(", "'-V'", ",", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%%(prog)s %s'", "%", "pkg_resources", ".", "get_distribution", "(", "\"aadbook\"", ")", ".", "version", ",", "help", "=", "\"Print version and exit\"", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--debug'", ",", "dest", "=", "\"log_level\"", ",", "action", "=", "'store_const'", ",", "const", "=", "logging", ".", "DEBUG", ",", "help", "=", "'Output debug info (stderr).'", ")", "parser", ".", "set_defaults", "(", "config", "=", "CONFIG_FILE", ",", "log_level", "=", "logging", ".", "ERROR", ")", "subparsers", "=", "parser", ".", "add_subparsers", "(", ")", "parser_config_template", "=", "subparsers", ".", "add_parser", "(", "'config-template'", ",", "description", "=", "'Prints a template for .aadbookrc to stdout'", ")", "parser_config_template", ".", "set_defaults", "(", "func", "=", "do_config_template", ")", "parser_reload", "=", "subparsers", ".", "add_parser", "(", "'authenticate'", ",", "description", "=", "'Azure AD authentication.'", ")", "parser_reload", ".", "set_defaults", "(", "func", "=", "do_authenticate", ")", "parser_reload", "=", "subparsers", ".", "add_parser", "(", "'reload'", ",", "description", "=", "'Force reload of the cache.'", ")", "parser_reload", ".", "set_defaults", "(", "func", "=", "do_reload", ")", "parser_query", "=", "subparsers", ".", "add_parser", "(", "'query'", ",", "description", "=", "'Search contacts using query (regex).'", ")", "parser_query", ".", "add_argument", "(", "'query'", ",", "help", "=", "'regex to search for.'", ",", "metavar", "=", "'QUERY'", ")", "parser_query", ".", "set_defaults", "(", "func", "=", "do_query", ")", "return", "parser" ]
This method will check if the given tag exists as a staging tag in the remote repository .
def check_existens_of_staging_tag_in_remote_repo ( ) : staging_tag = Git . create_git_version_tag ( APISettings . GIT_STAGING_PRE_TAG ) command_git = 'git ls-remote -t' command_awk = 'awk \'{print $2}\'' command_cut_1 = 'cut -d \'/\' -f 3' command_cut_2 = 'cut -d \'^\' -f 1' command_sort = 'sort -b -t . -k 1,1nr -k 2,2nr -k 3,3r -k 4,4r -k 5,5r' command_uniq = 'uniq' command = command_git + ' | ' + command_awk + ' | ' + command_cut_1 + ' | ' + command_cut_2 + ' | ' + command_sort + ' | ' + command_uniq list_of_tags = str ( check_output ( command , shell = True ) ) if staging_tag in list_of_tags : return True return False
8,849
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L40-L63
[ "def", "delay_and_stop", "(", "duration", ",", "dll", ",", "device_number", ")", ":", "xinput", "=", "getattr", "(", "ctypes", ".", "windll", ",", "dll", ")", "time", ".", "sleep", "(", "duration", "/", "1000", ")", "xinput_set_state", "=", "xinput", ".", "XInputSetState", "xinput_set_state", ".", "argtypes", "=", "[", "ctypes", ".", "c_uint", ",", "ctypes", ".", "POINTER", "(", "XinputVibration", ")", "]", "xinput_set_state", ".", "restype", "=", "ctypes", ".", "c_uint", "vibration", "=", "XinputVibration", "(", "0", ",", "0", ")", "xinput_set_state", "(", "device_number", ",", "ctypes", ".", "byref", "(", "vibration", ")", ")" ]
This method will be called if the debug mode is on .
def __debug ( command , dry = False ) : if dry : command . append ( '--dry-run' ) Shell . debug ( command ) if dry : call ( command ) exit ( 1 )
8,850
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L67-L78
[ "def", "render_category_averages", "(", "obj", ",", "normalize_to", "=", "100", ")", ":", "context", "=", "{", "'reviewed_item'", ":", "obj", "}", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "reviews", "=", "models", ".", "Review", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")", "category_averages", "=", "{", "}", "for", "review", "in", "reviews", ":", "review_category_averages", "=", "review", ".", "get_category_averages", "(", "normalize_to", ")", "if", "review_category_averages", ":", "for", "category", ",", "average", "in", "review_category_averages", ".", "items", "(", ")", ":", "if", "category", "not", "in", "category_averages", ":", "category_averages", "[", "category", "]", "=", "review_category_averages", "[", "category", "]", "else", ":", "category_averages", "[", "category", "]", "+=", "review_category_averages", "[", "category", "]", "if", "reviews", "and", "category_averages", ":", "for", "category", ",", "average", "in", "category_averages", ".", "items", "(", ")", ":", "category_averages", "[", "category", "]", "=", "category_averages", "[", "category", "]", "/", "models", ".", "Rating", ".", "objects", ".", "filter", "(", "category", "=", "category", ",", "value__isnull", "=", "False", ",", "review__content_type", "=", "ctype", ",", "review__object_id", "=", "obj", ".", "id", ")", ".", "exclude", "(", "value", "=", "''", ")", ".", "count", "(", ")", "else", ":", "category_averages", "=", "{", "}", "for", "category", "in", "models", ".", "RatingCategory", ".", "objects", ".", "filter", "(", "counts_for_average", "=", "True", ")", ":", "category_averages", "[", "category", "]", "=", "0.0", "context", ".", "update", "(", "{", "'category_averages'", ":", "category_averages", "}", ")", "return", "context" ]
Add files to staging . The function call will return 0 if the command success .
def __git_add ( args = '' ) : command = [ 'git' , 'add' , '.' ] Shell . msg ( 'Adding files...' ) if APISettings . DEBUG : Git . __debug ( command , True ) for key in args : command . append ( key ) if not call ( command ) : pass return False
8,851
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L83-L98
[ "def", "_get_optional_attrs", "(", "kws", ")", ":", "vals", "=", "OboOptionalAttrs", ".", "attributes", ".", "intersection", "(", "kws", ".", "keys", "(", ")", ")", "if", "'sections'", "in", "kws", ":", "vals", ".", "add", "(", "'relationship'", ")", "if", "'norel'", "in", "kws", ":", "vals", ".", "discard", "(", "'relationship'", ")", "return", "vals" ]
Commit files to branch . The function call will return 0 if the command success .
def __git_commit ( git_tag ) : Shell . msg ( 'Commit changes.' ) if APISettings . DEBUG : Shell . debug ( 'Execute "git commit" in dry mode.' ) if not call ( [ 'git' , 'commit' , '-m' , '\'' + git_tag + '\'' , '--dry-run' ] ) : pass return True if not call ( [ 'git' , 'commit' , '-m' , '\'' + git_tag + '\'' ] ) : return True return False
8,852
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L117-L131
[ "def", "read_avro", "(", "file_path_or_buffer", ",", "schema", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file_path_or_buffer", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "file_path_or_buffer", ",", "'rb'", ")", "as", "f", ":", "return", "__file_to_dataframe", "(", "f", ",", "schema", ",", "*", "*", "kwargs", ")", "else", ":", "return", "__file_to_dataframe", "(", "file_path_or_buffer", ",", "schema", ",", "*", "*", "kwargs", ")" ]
Create new tag . The function call will return 0 if the command success .
def __git_tag ( git_tag ) : command = [ 'git' , 'tag' , '-a' , git_tag , '-m' , '\'' + git_tag + '\'' ] Shell . msg ( 'Create tag from version ' + git_tag ) if APISettings . DEBUG : Git . __debug ( command , False ) if not call ( command ) : return True return False
8,853
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L135-L148
[ "def", "HeadList", "(", "self", ")", ":", "return", "[", "(", "rname", ",", "repo", ".", "currenthead", ")", "for", "rname", ",", "repo", "in", "self", ".", "repos", ".", "items", "(", ")", "]" ]
Push all tags . The function call will return 0 if the command success .
def __git_tag_push ( ) : command = [ 'git' , 'push' , 'origin' , '--tags' ] Shell . msg ( 'Pushing tags...' ) if APISettings . DEBUG : Git . __debug ( command , True ) if not call ( command ) : return True return False
8,854
https://github.com/rhazdon/django-sonic-screwdriver/blob/89e885e8c1322fc5c3e0f79b03a55acdc6e63972/django_sonic_screwdriver/git/git.py#L169-L182
[ "def", "HeadList", "(", "self", ")", ":", "return", "[", "(", "rname", ",", "repo", ".", "currenthead", ")", "for", "rname", ",", "repo", "in", "self", ".", "repos", ".", "items", "(", ")", "]" ]
Break the input data into smaller batches optionally saving each one to disk .
def split_into_batches ( input_list , batch_size , batch_storage_dir , checkpoint = False ) : if checkpoint and not os . path . exists ( batch_storage_dir ) : os . mkdir ( batch_storage_dir ) batches = [ { 'index' : batch_index , 'data' : input_list [ start_index : start_index + batch_size ] , 'input_filename' : os . path . join ( batch_storage_dir , 'batch-{:05d}-input.pickle' . format ( batch_index ) ) , 'result_filename' : os . path . join ( batch_storage_dir , 'batch-{:05d}-output.pickle' . format ( batch_index ) ) , } for batch_index , start_index in enumerate ( range ( 0 , len ( input_list ) , batch_size ) ) ] if checkpoint : for batch in batches : save ( batch [ 'data' ] , batch [ 'input_filename' ] ) return batches
8,855
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/jobs.py#L16-L48
[ "def", "result", "(", "self", ")", ":", "self", ".", "_reactor_check", "(", ")", "self", ".", "_event", ".", "wait", "(", ")", "if", "self", ".", "_exception", ":", "six", ".", "reraise", "(", "self", ".", "_exception", ".", "__class__", ",", "self", ".", "_exception", ",", "self", ".", "_traceback", ")", "if", "self", ".", "_result", "==", "NONE_RESULT", ":", "return", "None", "else", ":", "return", "self", ".", "_result" ]
Split the data into batches and process each batch in its own thread .
def map_batch_parallel ( input_list , batch_size , item_mapper = None , batch_mapper = None , flatten = True , n_jobs = - 1 , * * kwargs ) : # We must specify either how to process each batch or how to process each item. if item_mapper is None and batch_mapper is None : raise ValueError ( 'You should specify either batch_mapper or item_mapper.' ) if batch_mapper is None : batch_mapper = _default_batch_mapper batches = split_into_batches ( input_list , batch_size , batch_storage_dir = '' ) all_batch_results = Parallel ( n_jobs = n_jobs , * * kwargs ) ( delayed ( batch_mapper ) ( batch [ 'data' ] , item_mapper ) for batch in progressbar ( batches , desc = 'Batches' , total = len ( batches ) , file = sys . stdout , ) ) # Unwrap the individual batch results if necessary. if flatten : final_result = [ ] for batch_result in all_batch_results : final_result . extend ( batch_result ) else : final_result = all_batch_results return final_result
8,856
https://github.com/YuriyGuts/pygoose/blob/4d9b8827c6d6c4b79949d1cd653393498c0bb3c2/pygoose/kg/jobs.py#L110-L153
[ "def", "create_service_from_endpoint", "(", "endpoint", ",", "service_type", ",", "title", "=", "None", ",", "abstract", "=", "None", ",", "catalog", "=", "None", ")", ":", "from", "models", "import", "Service", "if", "Service", ".", "objects", ".", "filter", "(", "url", "=", "endpoint", ",", "catalog", "=", "catalog", ")", ".", "count", "(", ")", "==", "0", ":", "# check if endpoint is valid", "request", "=", "requests", ".", "get", "(", "endpoint", ")", "if", "request", ".", "status_code", "==", "200", ":", "LOGGER", ".", "debug", "(", "'Creating a %s service for endpoint=%s catalog=%s'", "%", "(", "service_type", ",", "endpoint", ",", "catalog", ")", ")", "service", "=", "Service", "(", "type", "=", "service_type", ",", "url", "=", "endpoint", ",", "title", "=", "title", ",", "abstract", "=", "abstract", ",", "csw_type", "=", "'service'", ",", "catalog", "=", "catalog", ")", "service", ".", "save", "(", ")", "return", "service", "else", ":", "LOGGER", ".", "warning", "(", "'This endpoint is invalid, status code is %s'", "%", "request", ".", "status_code", ")", "else", ":", "LOGGER", ".", "warning", "(", "'A service for this endpoint %s in catalog %s already exists'", "%", "(", "endpoint", ",", "catalog", ")", ")", "return", "None" ]
Traverses the AST and returns the corresponding CFG
def get_cfg ( ast_func ) : cfg_func = cfg . Function ( ) for ast_var in ast_func . input_variable_list : cfg_var = cfg_func . get_variable ( ast_var . name ) cfg_func . add_input_variable ( cfg_var ) for ast_var in ast_func . output_variable_list : cfg_var = cfg_func . get_variable ( ast_var . name ) cfg_func . add_output_variable ( cfg_var ) bb_start = cfg . BasicBlock ( ) cfg_func . add_basic_block ( bb_start ) for stmt in ast_func . body : bb_temp = bb_start bb_temp = process_cfg ( stmt , bb_temp , cfg_func ) cfg_func . clean_up ( ) cfg_func . add_summary ( ast_func . summary ) return cfg_func
8,857
https://github.com/anayjoshi/platypus/blob/71712f58c99651efbd2e6dfd75a9b1228d42e9ef/platypus/cfg/ast_to_cfg.py#L4-L28
[ "def", "ensure_compatible_admin", "(", "view", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "user_roles", "=", "request", ".", "user", ".", "user_data", ".", "get", "(", "'roles'", ",", "[", "]", ")", "if", "len", "(", "user_roles", ")", "!=", "1", ":", "context", "=", "{", "'message'", ":", "'I need to be able to manage user accounts. '", "'My username is %s'", "%", "request", ".", "user", ".", "username", "}", "return", "render", "(", "request", ",", "'mtp_common/user_admin/incompatible-admin.html'", ",", "context", "=", "context", ")", "return", "view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "wrapper" ]
like partial but given kwargs can be overrideden at calltime
def overrideable_partial ( func , * args , * * default_kwargs ) : import functools @ functools . wraps ( func ) def partial_wrapper ( * given_args , * * given_kwargs ) : kwargs = default_kwargs . copy ( ) kwargs . update ( given_kwargs ) return func ( * ( args + given_args ) , * * kwargs ) return partial_wrapper
8,858
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L40-L48
[ "def", "features_keep_using_features", "(", "obj", ",", "bounds", ")", ":", "# Build an R-tree index of bound features and their shapes.", "bounds_shapes", "=", "[", "(", "feature", ",", "shapely", ".", "geometry", ".", "shape", "(", "feature", "[", "'geometry'", "]", ")", ")", "for", "feature", "in", "tqdm", "(", "bounds", "[", "'features'", "]", ")", "if", "feature", "[", "'geometry'", "]", "is", "not", "None", "]", "index", "=", "rtree", ".", "index", ".", "Index", "(", ")", "for", "i", "in", "tqdm", "(", "range", "(", "len", "(", "bounds_shapes", ")", ")", ")", ":", "(", "feature", ",", "shape", ")", "=", "bounds_shapes", "[", "i", "]", "index", ".", "insert", "(", "i", ",", "shape", ".", "bounds", ")", "features_keep", "=", "[", "]", "for", "feature", "in", "tqdm", "(", "obj", "[", "'features'", "]", ")", ":", "if", "'geometry'", "in", "feature", "and", "'coordinates'", "in", "feature", "[", "'geometry'", "]", ":", "coordinates", "=", "feature", "[", "'geometry'", "]", "[", "'coordinates'", "]", "if", "any", "(", "[", "shape", ".", "contains", "(", "shapely", ".", "geometry", ".", "Point", "(", "lon", ",", "lat", ")", ")", "for", "(", "lon", ",", "lat", ")", "in", "coordinates", "for", "(", "feature", ",", "shape", ")", "in", "[", "bounds_shapes", "[", "i", "]", "for", "i", "in", "index", ".", "nearest", "(", "(", "lon", ",", "lat", ",", "lon", ",", "lat", ")", ",", "1", ")", "]", "]", ")", ":", "features_keep", ".", "append", "(", "feature", ")", "continue", "obj", "[", "'features'", "]", "=", "features_keep", "return", "obj" ]
gets a new string that wont conflict with something that already exists
def get_nonconflicting_string ( base_fmtstr , conflict_set , offset = 0 ) : # Infinite loop until we find a non-conflict conflict_set_ = set ( conflict_set ) for count in it . count ( offset ) : base_str = base_fmtstr % count if base_str not in conflict_set_ : return base_str
8,859
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L147-L175
[ "def", "_read_openephys", "(", "openephys_file", ")", ":", "root", "=", "ElementTree", ".", "parse", "(", "openephys_file", ")", ".", "getroot", "(", ")", "channels", "=", "[", "]", "for", "recording", "in", "root", ":", "s_freq", "=", "float", "(", "recording", ".", "attrib", "[", "'samplerate'", "]", ")", "for", "processor", "in", "recording", ":", "for", "channel", "in", "processor", ":", "channels", ".", "append", "(", "channel", ".", "attrib", ")", "return", "s_freq", ",", "channels" ]
r base_fmtstr must have a %d in it
def get_nonconflicting_path_old ( base_fmtstr , dpath , offset = 0 ) : import utool as ut from os . path import basename pattern = '*' dname_list = ut . glob ( dpath , pattern , recursive = False , with_files = True , with_dirs = True ) conflict_set = set ( [ basename ( dname ) for dname in dname_list ] ) newname = ut . get_nonconflicting_string ( base_fmtstr , conflict_set , offset = offset ) newpath = join ( dpath , newname ) return newpath
8,860
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L178-L193
[ "def", "cut", "(", "self", ",", "buffer", ")", ":", "from_", ",", "to", "=", "self", ".", "operator_range", "(", "buffer", ".", "document", ")", "from_", "+=", "buffer", ".", "cursor_position", "to", "+=", "buffer", ".", "cursor_position", "to", "-=", "1", "# SelectionState does not include the end position, `operator_range` does.", "document", "=", "Document", "(", "buffer", ".", "text", ",", "to", ",", "SelectionState", "(", "original_cursor_position", "=", "from_", ",", "type", "=", "self", ".", "selection_type", ")", ")", "new_document", ",", "clipboard_data", "=", "document", ".", "cut_selection", "(", ")", "return", "new_document", ",", "clipboard_data" ]
r Prompts user to accept or checks command line for - y
def are_you_sure ( msg = '' ) : print ( msg ) from utool import util_arg from utool import util_str override = util_arg . get_argflag ( ( '--yes' , '--y' , '-y' ) ) if override : print ( 'accepting based on command line flag' ) return True valid_ans = [ 'yes' , 'y' ] valid_prompt = util_str . conj_phrase ( valid_ans , 'or' ) ans = input ( 'Are you sure?\n Enter %s to accept\n' % valid_prompt ) return ans . lower ( ) in valid_ans
8,861
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1170-L1190
[ "def", "update", "(", "self", ",", "other", ")", ":", "self", ".", "update_ttl", "(", "other", ".", "ttl", ")", "super", "(", "Rdataset", ",", "self", ")", ".", "update", "(", "other", ")" ]
Gives user a window to stop a process before it happens
def grace_period ( msg = '' , seconds = 10 ) : import time print ( msg ) override = util_arg . get_argflag ( ( '--yes' , '--y' , '-y' ) ) print ( 'starting grace period' ) if override : print ( 'ending based on command line flag' ) return True for count in reversed ( range ( 1 , seconds + 1 ) ) : time . sleep ( 1 ) print ( '%d' % ( count , ) ) print ( '%d' % ( 0 , ) ) print ( 'grace period is over' ) return True
8,862
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1193-L1209
[ "def", "getPositionNearType", "(", "self", ",", "tagSet", ",", "idx", ")", ":", "try", ":", "return", "idx", "+", "self", ".", "__ambiguousTypes", "[", "idx", "]", ".", "getPositionByType", "(", "tagSet", ")", "except", "KeyError", ":", "raise", "error", ".", "PyAsn1Error", "(", "'Type position out of range'", ")" ]
template code for a infinte retry loop
def delayed_retry_gen ( delay_schedule = [ .1 , 1 , 10 ] , msg = None , timeout = None , raise_ = True ) : import utool as ut import time if not ut . isiterable ( delay_schedule ) : delay_schedule = [ delay_schedule ] tt = ut . tic ( ) # First attempt is immediate yield 0 for count in it . count ( 0 ) : #print('count = %r' % (count,)) if timeout is not None and ut . toc ( tt ) > timeout : if raise_ : raise Exception ( 'Retry loop timed out' ) else : raise StopIteration ( 'Retry loop timed out' ) index = min ( count , len ( delay_schedule ) - 1 ) delay = delay_schedule [ index ] time . sleep ( delay ) yield count + 1
8,863
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1212-L1233
[ "def", "roles_dict", "(", "path", ",", "repo_prefix", "=", "\"\"", ",", "repo_sub_dir", "=", "\"\"", ")", ":", "exit_if_path_not_found", "(", "path", ")", "aggregated_roles", "=", "{", "}", "roles", "=", "os", ".", "walk", "(", "path", ")", ".", "next", "(", ")", "[", "1", "]", "# First scan all directories", "for", "role", "in", "roles", ":", "for", "sub_role", "in", "roles_dict", "(", "path", "+", "\"/\"", "+", "role", ",", "repo_prefix", "=", "\"\"", ",", "repo_sub_dir", "=", "role", "+", "\"/\"", ")", ":", "aggregated_roles", "[", "role", "+", "\"/\"", "+", "sub_role", "]", "=", "role", "+", "\"/\"", "+", "sub_role", "# Then format them", "for", "role", "in", "roles", ":", "if", "is_role", "(", "os", ".", "path", ".", "join", "(", "path", ",", "role", ")", ")", ":", "if", "isinstance", "(", "role", ",", "basestring", ")", ":", "role_repo", "=", "\"{0}{1}\"", ".", "format", "(", "repo_prefix", ",", "role_name", "(", "role", ")", ")", "aggregated_roles", "[", "role", "]", "=", "role_repo", "return", "aggregated_roles" ]
Returns the string version of get_stats
def get_stats_str ( list_ = None , newlines = False , keys = None , exclude_keys = [ ] , lbl = None , precision = None , axis = 0 , stat_dict = None , use_nan = False , align = False , use_median = False , * * kwargs ) : from utool . util_str import repr4 import utool as ut # Get stats dict if stat_dict is None : stat_dict = get_stats ( list_ , axis = axis , use_nan = use_nan , use_median = use_median ) else : stat_dict = stat_dict . copy ( ) # Keep only included keys if specified if keys is not None : for key in list ( six . iterkeys ( stat_dict ) ) : if key not in keys : del stat_dict [ key ] # Remove excluded keys for key in exclude_keys : if key in stat_dict : del stat_dict [ key ] # apply precision statstr_dict = stat_dict . copy ( ) #precisionless_types = (bool,) + six.string_types if precision is not None : assert ut . is_int ( precision ) , 'precision must be an integer' float_fmtstr = '%.' + str ( precision ) + 'f' for key in list ( six . iterkeys ( statstr_dict ) ) : val = statstr_dict [ key ] isfloat = ut . is_float ( val ) if not isfloat and isinstance ( val , list ) : type_list = list ( map ( type , val ) ) if len ( type_list ) > 0 and ut . allsame ( type_list ) : if ut . is_float ( val [ 0 ] ) : isfloat = True val = np . array ( val ) if isfloat : if isinstance ( val , np . ndarray ) : strval = str ( [ float_fmtstr % v for v in val ] ) . replace ( '\'' , '' ) . lstrip ( 'u' ) #np.array_str((val), precision=precision) else : strval = float_fmtstr % val if not strval . startswith ( '0' ) : strval = strval . rstrip ( '0' ) strval = strval . rstrip ( '.' ) statstr_dict [ key ] = strval else : if isinstance ( val , np . ndarray ) : strval = repr ( val . tolist ( ) ) else : strval = str ( val ) statstr_dict [ key ] = strval # format the dictionary string stat_str = repr4 ( statstr_dict , strvals = True , newlines = newlines ) # add a label if requested if lbl is True : lbl = ut . get_varname_from_stack ( list_ , N = 1 ) # fancy if lbl is not None : stat_str = 'stats_' + lbl + ' = ' + stat_str if align : stat_str = ut . align ( stat_str , ':' ) return stat_str
8,864
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1430-L1520
[ "def", "flag", "(", "self", ",", "context", ")", ":", "lrow", ",", "urow", "=", "MS", ".", "row_extents", "(", "context", ")", "flag", "=", "self", ".", "_manager", ".", "ordered_main_table", ".", "getcol", "(", "MS", ".", "FLAG", ",", "startrow", "=", "lrow", ",", "nrow", "=", "urow", "-", "lrow", ")", "return", "flag", ".", "reshape", "(", "context", ".", "shape", ")", ".", "astype", "(", "context", ".", "dtype", ")" ]
profile with pycallgraph
def make_call_graph ( func , * args , * * kwargs ) : from pycallgraph import PyCallGraph from pycallgraph . output import GraphvizOutput with PyCallGraph ( output = GraphvizOutput ) : func ( * args , * * kwargs )
8,865
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1549-L1561
[ "def", "Update", "(", "self", ",", "size", ")", ":", "if", "self", ".", "_msg", "is", "None", ":", "return", "help_msg", "=", "self", ".", "_msg", "width", ",", "height", "=", "size", "content_area", "=", "int", "(", "(", "width", "/", "3", ")", "*", ".70", ")", "wiggle_room", "=", "range", "(", "int", "(", "content_area", "-", "content_area", "*", ".05", ")", ",", "int", "(", "content_area", "+", "content_area", "*", ".05", ")", ")", "if", "help_msg", ".", "Size", "[", "0", "]", "not", "in", "wiggle_room", ":", "self", ".", "_msg", ".", "SetLabel", "(", "self", ".", "_msg", ".", "GetLabelText", "(", ")", ".", "replace", "(", "'\\n'", ",", "' '", ")", ")", "self", ".", "_msg", ".", "Wrap", "(", "content_area", ")" ]
Helper for memory debugging . Mostly just a namespace where I experiment with guppy and heapy .
def _memory_profile ( with_gc = False ) : import utool as ut if with_gc : garbage_collect ( ) import guppy hp = guppy . hpy ( ) print ( '[hpy] Waiting for heap output...' ) heap_output = hp . heap ( ) print ( heap_output ) print ( '[hpy] total heap size: ' + ut . byte_str2 ( heap_output . size ) ) ut . util_resources . memstats ( )
8,866
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1586-L1607
[ "def", "get_relations", "(", "self", ",", "service_title", ",", "default_obj", ",", "obj_type", ",", "catalog_name", ",", "sheet_name", ",", "column", ")", ":", "out_objects", "=", "[", "default_obj", "]", "if", "default_obj", "else", "[", "]", "cat", "=", "getToolByName", "(", "self", ".", "context", ",", "catalog_name", ")", "worksheet", "=", "self", ".", "workbook", ".", "get_sheet_by_name", "(", "sheet_name", ")", "if", "not", "worksheet", ":", "return", "out_objects", "for", "row", "in", "self", ".", "get_rows", "(", "3", ",", "worksheet", "=", "worksheet", ")", ":", "row_as_title", "=", "row", ".", "get", "(", "'Service_title'", ")", "if", "not", "row_as_title", ":", "return", "out_objects", "elif", "row_as_title", "!=", "service_title", ":", "continue", "obj", "=", "self", ".", "get_object", "(", "cat", ",", "obj_type", ",", "row", ".", "get", "(", "column", ")", ")", "if", "obj", ":", "if", "default_obj", "and", "default_obj", ".", "UID", "(", ")", "==", "obj", ".", "UID", "(", ")", ":", "continue", "out_objects", ".", "append", "(", "obj", ")", "return", "out_objects" ]
memoryprofile with objgraph
def make_object_graph ( obj , fpath = 'sample_graph.png' ) : import objgraph objgraph . show_most_common_types ( ) #print(objgraph.by_type('ndarray')) #objgraph.find_backref_chain( # random.choice(objgraph.by_type('ndarray')), # objgraph.is_proper_module) objgraph . show_refs ( [ obj ] , filename = 'ref_graph.png' ) objgraph . show_backrefs ( [ obj ] , filename = 'backref_graph.png' )
8,867
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L1612-L1640
[ "def", "svd", "(", "stream_list", ",", "full", "=", "False", ")", ":", "# Convert templates into ndarrays for each channel", "# First find all unique channels:", "stachans", "=", "list", "(", "set", "(", "[", "(", "tr", ".", "stats", ".", "station", ",", "tr", ".", "stats", ".", "channel", ")", "for", "st", "in", "stream_list", "for", "tr", "in", "st", "]", ")", ")", "stachans", ".", "sort", "(", ")", "# Initialize a list for the output matrices, one matrix per-channel", "svalues", "=", "[", "]", "svectors", "=", "[", "]", "uvectors", "=", "[", "]", "for", "stachan", "in", "stachans", ":", "lengths", "=", "[", "]", "for", "st", "in", "stream_list", ":", "tr", "=", "st", ".", "select", "(", "station", "=", "stachan", "[", "0", "]", ",", "channel", "=", "stachan", "[", "1", "]", ")", "if", "len", "(", "tr", ")", ">", "0", ":", "tr", "=", "tr", "[", "0", "]", "else", ":", "warnings", ".", "warn", "(", "'Stream does not contain %s'", "%", "'.'", ".", "join", "(", "list", "(", "stachan", ")", ")", ")", "continue", "lengths", ".", "append", "(", "len", "(", "tr", ".", "data", ")", ")", "min_length", "=", "min", "(", "lengths", ")", "for", "stream", "in", "stream_list", ":", "chan", "=", "stream", ".", "select", "(", "station", "=", "stachan", "[", "0", "]", ",", "channel", "=", "stachan", "[", "1", "]", ")", "if", "chan", ":", "if", "len", "(", "chan", "[", "0", "]", ".", "data", ")", ">", "min_length", ":", "if", "abs", "(", "len", "(", "chan", "[", "0", "]", ".", "data", ")", "-", "min_length", ")", ">", "0.1", "*", "chan", "[", "0", "]", ".", "stats", ".", "sampling_rate", ":", "raise", "IndexError", "(", "'More than 0.1 s length '", "'difference, align and fix'", ")", "warnings", ".", "warn", "(", "'Channels are not equal length, trimming'", ")", "chan", "[", "0", "]", ".", "data", "=", "chan", "[", "0", "]", ".", "data", "[", "0", ":", "min_length", "]", "if", "'chan_mat'", "not", "in", "locals", "(", ")", ":", "chan_mat", "=", "chan", "[", "0", "]", ".", "data", "else", ":", "chan_mat", "=", "np", ".", "vstack", "(", "(", "chan_mat", ",", "chan", "[", "0", "]", ".", "data", ")", ")", "if", "not", "len", "(", "chan_mat", ".", "shape", ")", ">", "1", ":", "warnings", ".", "warn", "(", "'Matrix of traces is less than 2D for %s'", "%", "'.'", ".", "join", "(", "list", "(", "stachan", ")", ")", ")", "continue", "# Be sure to transpose chan_mat as waveforms must define columns", "chan_mat", "=", "np", ".", "asarray", "(", "chan_mat", ")", "u", ",", "s", ",", "v", "=", "np", ".", "linalg", ".", "svd", "(", "chan_mat", ".", "T", ",", "full_matrices", "=", "full", ")", "svalues", ".", "append", "(", "s", ")", "svectors", ".", "append", "(", "v", ")", "uvectors", ".", "append", "(", "u", ")", "del", "(", "chan_mat", ")", "return", "uvectors", ",", "svalues", ",", "svectors", ",", "stachans" ]
item1_list = aid1_list item2_list = aid2_list
def inverable_unique_two_lists ( item1_list , item2_list ) : import utool as ut unique_list1 , inverse1 = np . unique ( item1_list , return_inverse = True ) unique_list2 , inverse2 = np . unique ( item2_list , return_inverse = True ) flat_stacked , cumsum = ut . invertible_flatten2 ( ( unique_list1 , unique_list2 ) ) flat_unique , inverse3 = np . unique ( flat_stacked , return_inverse = True ) reconstruct_tup = ( inverse3 , cumsum , inverse2 , inverse1 ) return flat_unique , reconstruct_tup
8,868
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2151-L2163
[ "def", "setup_main_logger", "(", "file_logging", "=", "True", ",", "console", "=", "True", ",", "path", ":", "Optional", "[", "str", "]", "=", "None", ",", "level", "=", "logging", ".", "INFO", ")", ":", "if", "file_logging", "and", "console", ":", "log_config", "=", "LOGGING_CONFIGS", "[", "\"file_console\"", "]", "# type: ignore", "elif", "file_logging", ":", "log_config", "=", "LOGGING_CONFIGS", "[", "\"file_only\"", "]", "elif", "console", ":", "log_config", "=", "LOGGING_CONFIGS", "[", "\"console_only\"", "]", "else", ":", "log_config", "=", "LOGGING_CONFIGS", "[", "\"none\"", "]", "if", "path", ":", "log_config", "[", "\"handlers\"", "]", "[", "\"rotating\"", "]", "[", "\"filename\"", "]", "=", "path", "# type: ignore", "for", "_", ",", "handler_config", "in", "log_config", "[", "'handlers'", "]", ".", "items", "(", ")", ":", "# type: ignore", "handler_config", "[", "'level'", "]", "=", "level", "logging", ".", "config", ".", "dictConfig", "(", "log_config", ")", "# type: ignore", "def", "exception_hook", "(", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", ":", "if", "is_python34", "(", ")", ":", "# Python3.4 does not seem to handle logger.exception() well", "import", "traceback", "traceback", "=", "\"\"", ".", "join", "(", "traceback", ".", "format_tb", "(", "exc_traceback", ")", ")", "+", "exc_type", ".", "name", "logging", ".", "error", "(", "\"Uncaught exception\\n%s\"", ",", "traceback", ")", "else", ":", "logging", ".", "exception", "(", "\"Uncaught exception\"", ",", "exc_info", "=", "(", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", ")", "sys", ".", "excepthook", "=", "exception_hook" ]
flat_list = thumb_list
def uninvert_unique_two_lists ( flat_list , reconstruct_tup ) : import utool as ut ( inverse3 , cumsum , inverse2 , inverse1 ) = reconstruct_tup flat_stacked_ = ut . take ( flat_list , inverse3 ) unique_list1_ , unique_list2_ = ut . unflatten2 ( flat_stacked_ , cumsum ) res_list1_ = ut . take ( unique_list1_ , inverse1 ) res_list2_ = ut . take ( unique_list2_ , inverse2 ) return res_list1_ , res_list2_
8,869
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2166-L2176
[ "def", "_any_source_silent", "(", "sources", ")", ":", "return", "np", ".", "any", "(", "np", ".", "all", "(", "np", ".", "sum", "(", "sources", ",", "axis", "=", "tuple", "(", "range", "(", "2", ",", "sources", ".", "ndim", ")", ")", ")", "==", "0", ",", "axis", "=", "1", ")", ")" ]
r Searches module functions classes and constants for members matching a pattern .
def search_module ( mod , pat , ignore_case = True , recursive = False , _seen = None ) : if _seen is not None and mod in _seen : return [ ] import utool as ut reflags = re . IGNORECASE * ignore_case found_list = [ name for name in dir ( mod ) if re . search ( pat , name , flags = reflags ) ] if recursive : if _seen is None : _seen = set ( ) _seen . add ( mod ) module_attrs = [ getattr ( mod , name ) for name in dir ( mod ) ] submodules = [ submod for submod in module_attrs if isinstance ( submod , types . ModuleType ) and submod not in _seen and ut . is_defined_by_module ( submod , mod ) ] for submod in submodules : found_list += search_module ( submod , pat , ignore_case = ignore_case , recursive = recursive , _seen = _seen ) # found_list = [name for name in dir(mod) if name.find(pat) >= 0] found_list = ut . unique_ordered ( found_list ) return found_list
8,870
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2268-L2325
[ "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", "]" ]
Executes methods and attribute calls on a list of objects of the same type
def instancelist ( obj_list , check = False , shared_attrs = None ) : class InstanceList_ ( object ) : def __init__ ( self , obj_list , shared_attrs = None ) : self . _obj_list = [ ] self . _shared_public_attrs = [ ] self . _example_type = None if len ( obj_list ) > 0 : import utool as ut self . _obj_list = obj_list example_obj = obj_list [ 0 ] example_type = type ( example_obj ) self . _example_type = example_type if shared_attrs is None : if check : attrsgen = [ set ( dir ( obj ) ) for obj in obj_list ] shared_attrs = list ( reduce ( set . intersection , attrsgen ) ) else : shared_attrs = dir ( example_obj ) #allowed = ['__getitem__'] # TODO, put in metaclass allowed = [ ] self . _shared_public_attrs = [ a for a in shared_attrs if a in allowed or not a . startswith ( '_' ) ] for attrname in self . _shared_public_attrs : attrtype = getattr ( example_type , attrname , None ) if attrtype is not None and isinstance ( attrtype , property ) : # need to do this as metaclass setattr ( InstanceList_ , attrname , property ( self . _define_prop ( attrname ) ) ) else : func = self . _define_func ( attrname ) ut . inject_func_as_method ( self , func , attrname ) def __nice__ ( self ) : if self . _example_type is None : typename = 'object' else : typename = self . _example_type . __name__ return 'of %d %s(s)' % ( len ( self . _obj_list ) , typename ) def __repr__ ( self ) : classname = self . __class__ . __name__ devnice = self . __nice__ ( ) return '<%s(%s) at %s>' % ( classname , devnice , hex ( id ( self ) ) ) def __str__ ( self ) : classname = self . __class__ . __name__ devnice = self . __nice__ ( ) return '<%s(%s)>' % ( classname , devnice ) def __getitem__ ( self , key ) : # TODO, put in metaclass return self . _map_method ( '__getitem__' , key ) def _define_func ( self , attrname ) : import utool as ut def _wrapper ( self , * args , * * kwargs ) : return self . _map_method ( attrname , * args , * * kwargs ) ut . set_funcname ( _wrapper , attrname ) return _wrapper def _map_method ( self , attrname , * args , * * kwargs ) : mapped_vals = [ getattr ( obj , attrname ) ( * args , * * kwargs ) for obj in self . _obj_list ] return mapped_vals def _define_prop ( self , attrname ) : import utool as ut def _getter ( self ) : return self . _map_property ( attrname ) ut . set_funcname ( _getter , 'get_' + attrname ) return _getter def _map_property ( self , attrname ) : mapped_vals = [ getattr ( obj , attrname ) for obj in self . _obj_list ] return mapped_vals return InstanceList_ ( obj_list , shared_attrs )
8,871
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2570-L2672
[ "def", "get_segment_definer_comments", "(", "xml_file", ",", "include_version", "=", "True", ")", ":", "from", "glue", ".", "ligolw", ".", "ligolw", "import", "LIGOLWContentHandler", "as", "h", "lsctables", ".", "use_in", "(", "h", ")", "# read segment definer table", "xmldoc", ",", "_", "=", "ligolw_utils", ".", "load_fileobj", "(", "xml_file", ",", "gz", "=", "xml_file", ".", "name", ".", "endswith", "(", "\".gz\"", ")", ",", "contenthandler", "=", "h", ")", "seg_def_table", "=", "table", ".", "get_table", "(", "xmldoc", ",", "lsctables", ".", "SegmentDefTable", ".", "tableName", ")", "# put comment column into a dict", "comment_dict", "=", "{", "}", "for", "seg_def", "in", "seg_def_table", ":", "if", "include_version", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", ",", "str", "(", "seg_def", ".", "version", ")", "]", ")", "else", ":", "full_channel_name", "=", "':'", ".", "join", "(", "[", "str", "(", "seg_def", ".", "ifos", ")", ",", "str", "(", "seg_def", ".", "name", ")", "]", ")", "comment_dict", "[", "full_channel_name", "]", "=", "seg_def", ".", "comment", "return", "comment_dict" ]
why is this not in heapq
def _heappush_max ( heap , item ) : heap . append ( item ) heapq . _siftdown_max ( heap , 0 , len ( heap ) - 1 )
8,872
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L3235-L3238
[ "def", "handle_extra_source", "(", "self", ",", "source_df", ",", "sim_params", ")", ":", "if", "source_df", "is", "None", ":", "return", "# Normalize all the dates in the df", "source_df", ".", "index", "=", "source_df", ".", "index", ".", "normalize", "(", ")", "# source_df's sid column can either consist of assets we know about", "# (such as sid(24)) or of assets we don't know about (such as", "# palladium).", "#", "# In both cases, we break up the dataframe into individual dfs", "# that only contain a single asset's information. ie, if source_df", "# has data for PALLADIUM and GOLD, we split source_df into two", "# dataframes, one for each. (same applies if source_df has data for", "# AAPL and IBM).", "#", "# We then take each child df and reindex it to the simulation's date", "# range by forward-filling missing values. this makes reads simpler.", "#", "# Finally, we store the data. For each column, we store a mapping in", "# self.augmented_sources_map from the column to a dictionary of", "# asset -> df. In other words,", "# self.augmented_sources_map['days_to_cover']['AAPL'] gives us the df", "# holding that data.", "source_date_index", "=", "self", ".", "trading_calendar", ".", "sessions_in_range", "(", "sim_params", ".", "start_session", ",", "sim_params", ".", "end_session", ")", "# Break the source_df up into one dataframe per sid. This lets", "# us (more easily) calculate accurate start/end dates for each sid,", "# de-dup data, and expand the data to fit the backtest start/end date.", "grouped_by_sid", "=", "source_df", ".", "groupby", "(", "[", "\"sid\"", "]", ")", "group_names", "=", "grouped_by_sid", ".", "groups", ".", "keys", "(", ")", "group_dict", "=", "{", "}", "for", "group_name", "in", "group_names", ":", "group_dict", "[", "group_name", "]", "=", "grouped_by_sid", ".", "get_group", "(", "group_name", ")", "# This will be the dataframe which we query to get fetcher assets at", "# any given time. Get's overwritten every time there's a new fetcher", "# call", "extra_source_df", "=", "pd", ".", "DataFrame", "(", ")", "for", "identifier", ",", "df", "in", "iteritems", "(", "group_dict", ")", ":", "# Since we know this df only contains a single sid, we can safely", "# de-dupe by the index (dt). If minute granularity, will take the", "# last data point on any given day", "df", "=", "df", ".", "groupby", "(", "level", "=", "0", ")", ".", "last", "(", ")", "# Reindex the dataframe based on the backtest start/end date.", "# This makes reads easier during the backtest.", "df", "=", "self", ".", "_reindex_extra_source", "(", "df", ",", "source_date_index", ")", "for", "col_name", "in", "df", ".", "columns", ".", "difference", "(", "[", "'sid'", "]", ")", ":", "if", "col_name", "not", "in", "self", ".", "_augmented_sources_map", ":", "self", ".", "_augmented_sources_map", "[", "col_name", "]", "=", "{", "}", "self", ".", "_augmented_sources_map", "[", "col_name", "]", "[", "identifier", "]", "=", "df", "# Append to extra_source_df the reindexed dataframe for the single", "# sid", "extra_source_df", "=", "extra_source_df", ".", "append", "(", "df", ")", "self", ".", "_extra_source_df", "=", "extra_source_df" ]
Takes a subset of columns
def take_column ( self , keys , * extra_keys ) : import utool as ut keys = ut . ensure_iterable ( keys ) + list ( extra_keys ) key_to_list = ut . dict_subset ( self . _key_to_list , keys ) newself = self . __class__ ( key_to_list , self . _meta . copy ( ) ) return newself
8,873
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2830-L2836
[ "def", "load_toml_rest_api_config", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "LOGGER", ".", "info", "(", "\"Skipping rest api loading from non-existent config file: %s\"", ",", "filename", ")", "return", "RestApiConfig", "(", ")", "LOGGER", ".", "info", "(", "\"Loading rest api information from config: %s\"", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "fd", ":", "raw_config", "=", "fd", ".", "read", "(", ")", "except", "IOError", "as", "e", ":", "raise", "RestApiConfigurationError", "(", "\"Unable to load rest api configuration file: {}\"", ".", "format", "(", "str", "(", "e", ")", ")", ")", "toml_config", "=", "toml", ".", "loads", "(", "raw_config", ")", "invalid_keys", "=", "set", "(", "toml_config", ".", "keys", "(", ")", ")", ".", "difference", "(", "[", "'bind'", ",", "'connect'", ",", "'timeout'", ",", "'opentsdb_db'", ",", "'opentsdb_url'", ",", "'opentsdb_username'", ",", "'opentsdb_password'", ",", "'client_max_size'", "]", ")", "if", "invalid_keys", ":", "raise", "RestApiConfigurationError", "(", "\"Invalid keys in rest api config: {}\"", ".", "format", "(", "\", \"", ".", "join", "(", "sorted", "(", "list", "(", "invalid_keys", ")", ")", ")", ")", ")", "config", "=", "RestApiConfig", "(", "bind", "=", "toml_config", ".", "get", "(", "\"bind\"", ",", "None", ")", ",", "connect", "=", "toml_config", ".", "get", "(", "'connect'", ",", "None", ")", ",", "timeout", "=", "toml_config", ".", "get", "(", "'timeout'", ",", "None", ")", ",", "opentsdb_url", "=", "toml_config", ".", "get", "(", "'opentsdb_url'", ",", "None", ")", ",", "opentsdb_db", "=", "toml_config", ".", "get", "(", "'opentsdb_db'", ",", "None", ")", ",", "opentsdb_username", "=", "toml_config", ".", "get", "(", "'opentsdb_username'", ",", "None", ")", ",", "opentsdb_password", "=", "toml_config", ".", "get", "(", "'opentsdb_password'", ",", "None", ")", ",", "client_max_size", "=", "toml_config", ".", "get", "(", "'client_max_size'", ",", "None", ")", ")", "return", "config" ]
Takes a subset of rows
def take ( self , idxs ) : import utool as ut if False : key_to_list = ut . odict ( [ ( key , ut . take ( val , idxs ) ) for key , val in six . iteritems ( self . _key_to_list ) ] ) else : import numpy as np key_to_list = ut . odict ( [ ( key , ut . take ( val , idxs ) ) if not isinstance ( val , np . ndarray ) else val . take ( idxs , axis = 0 ) for key , val in six . iteritems ( self . _key_to_list ) ] ) newself = self . __class__ ( key_to_list , self . _meta . copy ( ) ) return newself
8,874
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2838-L2855
[ "def", "_sendStatCmd", "(", "self", ",", "cmd", ")", ":", "try", ":", "self", ".", "_conn", ".", "write", "(", "\"%s\\r\\n\"", "%", "cmd", ")", "regex", "=", "re", ".", "compile", "(", "'^(END|ERROR)\\r\\n'", ",", "re", ".", "MULTILINE", ")", "(", "idx", ",", "mobj", ",", "text", ")", "=", "self", ".", "_conn", ".", "expect", "(", "[", "regex", ",", "]", ",", "self", ".", "_timeout", ")", "#@UnusedVariable", "except", ":", "raise", "Exception", "(", "\"Communication with %s failed\"", "%", "self", ".", "_instanceName", ")", "if", "mobj", "is", "not", "None", ":", "if", "mobj", ".", "group", "(", "1", ")", "==", "'END'", ":", "return", "text", ".", "splitlines", "(", ")", "[", ":", "-", "1", "]", "elif", "mobj", ".", "group", "(", "1", ")", "==", "'ERROR'", ":", "raise", "Exception", "(", "\"Protocol error in communication with %s.\"", "%", "self", ".", "_instanceName", ")", "else", ":", "raise", "Exception", "(", "\"Connection with %s timed out.\"", "%", "self", ".", "_instanceName", ")" ]
Returns a copy with idxs removed
def remove ( self , idxs ) : import utool as ut keep_idxs = ut . index_complement ( idxs , len ( self ) ) return self . take ( keep_idxs )
8,875
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2857-L2861
[ "def", "render_parse_load", "(", "raw_config", ",", "environment", "=", "None", ",", "validate", "=", "True", ")", ":", "pre_rendered", "=", "render", "(", "raw_config", ",", "environment", ")", "rendered", "=", "process_remote_sources", "(", "pre_rendered", ",", "environment", ")", "config", "=", "parse", "(", "rendered", ")", "# For backwards compatibility, if the config doesn't specify a namespace,", "# we fall back to fetching it from the environment, if provided.", "if", "config", ".", "namespace", "is", "None", ":", "namespace", "=", "environment", ".", "get", "(", "\"namespace\"", ")", "if", "namespace", ":", "logger", ".", "warn", "(", "\"DEPRECATION WARNING: specifying namespace in the \"", "\"environment is deprecated. See \"", "\"https://stacker.readthedocs.io/en/latest/config.html\"", "\"#namespace \"", "\"for more info.\"", ")", "config", ".", "namespace", "=", "namespace", "if", "validate", ":", "config", ".", "validate", "(", ")", "return", "load", "(", "config", ")" ]
group as dict
def group_items ( self , labels ) : import utool as ut unique_labels , groups = self . group ( labels ) label_to_group = ut . odict ( zip ( unique_labels , groups ) ) return label_to_group
8,876
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2880-L2885
[ "def", "console", "(", "self", ",", "console", ")", ":", "if", "console", "==", "self", ".", "_console", ":", "return", "if", "self", ".", "_console_type", "==", "\"vnc\"", "and", "console", "is", "not", "None", "and", "console", "<", "5900", ":", "raise", "NodeError", "(", "\"VNC console require a port superior or equal to 5900 currently it's {}\"", ".", "format", "(", "console", ")", ")", "if", "self", ".", "_console", ":", "self", ".", "_manager", ".", "port_manager", ".", "release_tcp_port", "(", "self", ".", "_console", ",", "self", ".", "_project", ")", "self", ".", "_console", "=", "None", "if", "console", "is", "not", "None", ":", "if", "self", ".", "console_type", "==", "\"vnc\"", ":", "self", ".", "_console", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "console", ",", "self", ".", "_project", ",", "port_range_start", "=", "5900", ",", "port_range_end", "=", "6000", ")", "else", ":", "self", ".", "_console", "=", "self", ".", "_manager", ".", "port_manager", ".", "reserve_tcp_port", "(", "console", ",", "self", ".", "_project", ")", "log", ".", "info", "(", "\"{module}: '{name}' [{id}]: console port set to {port}\"", ".", "format", "(", "module", "=", "self", ".", "manager", ".", "module_name", ",", "name", "=", "self", ".", "name", ",", "id", "=", "self", ".", "id", ",", "port", "=", "console", ")", ")" ]
group as list
def group ( self , labels ) : unique_labels , groupxs = self . group_indicies ( labels ) groups = [ self . take ( idxs ) for idxs in groupxs ] return unique_labels , groups
8,877
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2887-L2891
[ "def", "_wget", "(", "cmd", ",", "opts", "=", "None", ",", "url", "=", "'http://localhost:8080/manager'", ",", "timeout", "=", "180", ")", ":", "ret", "=", "{", "'res'", ":", "True", ",", "'msg'", ":", "[", "]", "}", "# prepare authentication", "auth", "=", "_auth", "(", "url", ")", "if", "auth", "is", "False", ":", "ret", "[", "'res'", "]", "=", "False", "ret", "[", "'msg'", "]", "=", "'missing username and password settings (grain/pillar)'", "return", "ret", "# prepare URL", "if", "url", "[", "-", "1", "]", "!=", "'/'", ":", "url", "+=", "'/'", "url6", "=", "url", "url", "+=", "'text/{0}'", ".", "format", "(", "cmd", ")", "url6", "+=", "'{0}'", ".", "format", "(", "cmd", ")", "if", "opts", ":", "url", "+=", "'?{0}'", ".", "format", "(", "_urlencode", "(", "opts", ")", ")", "url6", "+=", "'?{0}'", ".", "format", "(", "_urlencode", "(", "opts", ")", ")", "# Make the HTTP request", "_install_opener", "(", "auth", ")", "try", ":", "# Trying tomcat >= 7 url", "ret", "[", "'msg'", "]", "=", "_urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", "except", "Exception", ":", "try", ":", "# Trying tomcat6 url", "ret", "[", "'msg'", "]", "=", "_urlopen", "(", "url6", ",", "timeout", "=", "timeout", ")", ".", "read", "(", ")", ".", "splitlines", "(", ")", "except", "Exception", ":", "ret", "[", "'msg'", "]", "=", "'Failed to create HTTP request'", "if", "not", "ret", "[", "'msg'", "]", "[", "0", "]", ".", "startswith", "(", "'OK'", ")", ":", "ret", "[", "'res'", "]", "=", "False", "return", "ret" ]
like map column but applies values inplace
def cast_column ( self , keys , func ) : import utool as ut for key in ut . ensure_iterable ( keys ) : self [ key ] = [ func ( v ) for v in self [ key ] ]
8,878
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2919-L2923
[ "def", "get_attached_instruments", "(", "self", ",", "expected", ":", "Dict", "[", "Mount", ",", "str", "]", ")", "->", "Dict", "[", "Mount", ",", "Dict", "[", "str", ",", "Optional", "[", "str", "]", "]", "]", ":", "to_return", ":", "Dict", "[", "Mount", ",", "Dict", "[", "str", ",", "Optional", "[", "str", "]", "]", "]", "=", "{", "}", "for", "mount", "in", "Mount", ":", "found_model", "=", "self", ".", "_smoothie_driver", ".", "read_pipette_model", "(", "mount", ".", "name", ".", "lower", "(", ")", ")", "found_id", "=", "self", ".", "_smoothie_driver", ".", "read_pipette_id", "(", "mount", ".", "name", ".", "lower", "(", ")", ")", "expected_instr", "=", "expected", ".", "get", "(", "mount", ",", "None", ")", "if", "expected_instr", "and", "(", "not", "found_model", "or", "not", "found_model", ".", "startswith", "(", "expected_instr", ")", ")", ":", "raise", "RuntimeError", "(", "'mount {}: instrument {} was requested but {} is present'", ".", "format", "(", "mount", ".", "name", ",", "expected_instr", ",", "found_model", ")", ")", "to_return", "[", "mount", "]", "=", "{", "'model'", ":", "found_model", ",", "'id'", ":", "found_id", "}", "return", "to_return" ]
Uses key as a unique index an merges all duplicates rows . Use cast_column to modify types of columns before merging to affect behavior of duplicate rectification .
def merge_rows ( self , key , merge_scalars = True ) : import utool as ut unique_labels , groupxs = self . group_indicies ( key ) single_xs = [ xs for xs in groupxs if len ( xs ) == 1 ] multi_xs = [ xs for xs in groupxs if len ( xs ) > 1 ] singles = self . take ( ut . flatten ( single_xs ) ) multis = [ self . take ( idxs ) for idxs in multi_xs ] merged_groups = [ ] for group in multis : newgroup = { } for key_ in group . keys ( ) : val = group [ key_ ] if key_ == key : # key_ was garuenteed unique val_ = val [ 0 ] elif hasattr ( val [ 0 ] . __class__ , 'union' ) : # HACK # Sets are unioned val_ = ut . oset . union ( * val ) elif isinstance ( val [ 0 ] , ( ut . oset , ) ) : # Sets are unioned val_ = ut . oset . union ( * val ) elif isinstance ( val [ 0 ] , ( set ) ) : # Sets are unioned val_ = set . union ( * val ) elif isinstance ( val [ 0 ] , ( tuple , list ) ) : # Lists are merged together val_ = ut . flatten ( val ) #val_ = ut.unique(ut.flatten(val)) else : if ut . allsame ( val ) : # Merge items that are the same val_ = val [ 0 ] else : if merge_scalars : # If mergeing scalars is ok, then # Values become lists if they are different val_ = val else : if True : # If there is only one non-none value then use that. other_vals = ut . filter_Nones ( val ) if len ( other_vals ) == 1 : val_ = val [ 0 ] else : raise ValueError ( 'tried to merge a scalar in %r, val=%r' % ( key_ , val ) ) else : # If merging scalars is not ok, then # we must raise an error raise ValueError ( 'tried to merge a scalar in %r, val=%r' % ( key_ , val ) ) newgroup [ key_ ] = [ val_ ] merged_groups . append ( ut . ColumnLists ( newgroup ) ) merged_multi = self . __class__ . flatten ( merged_groups ) merged = singles + merged_multi return merged
8,879
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L2934-L3024
[ "def", "ReadVFS", "(", "pathspec", ",", "offset", ",", "length", ",", "progress_callback", "=", "None", ")", ":", "fd", "=", "VFSOpen", "(", "pathspec", ",", "progress_callback", "=", "progress_callback", ")", "fd", ".", "Seek", "(", "offset", ")", "return", "fd", ".", "Read", "(", "length", ")" ]
Peek at the next item in the queue
def peek ( self ) : # Ammortized O(1) _heap = self . _heap _dict = self . _dict val , key = _heap [ 0 ] # Remove items marked for lazy deletion as they are encountered while key not in _dict or _dict [ key ] != val : self . _heappop ( _heap ) val , key = _heap [ 0 ] return key , val
8,880
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L3363-L3375
[ "def", "_get_license_description", "(", "license_code", ")", ":", "req", "=", "requests", ".", "get", "(", "\"{base_url}/licenses/{license_code}\"", ".", "format", "(", "base_url", "=", "BASE_URL", ",", "license_code", "=", "license_code", ")", ",", "headers", "=", "_HEADERS", ")", "if", "req", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "s", "=", "req", ".", "json", "(", ")", "[", "\"body\"", "]", "search_curly", "=", "re", ".", "search", "(", "r'\\{(.*)\\}'", ",", "s", ")", "search_square", "=", "re", ".", "search", "(", "r'\\[(.*)\\]'", ",", "s", ")", "license", "=", "\"\"", "replace_string", "=", "'{year} {name}'", ".", "format", "(", "year", "=", "date", ".", "today", "(", ")", ".", "year", ",", "name", "=", "_get_config_name", "(", ")", ")", "if", "search_curly", ":", "license", "=", "re", ".", "sub", "(", "r'\\{(.+)\\}'", ",", "replace_string", ",", "s", ")", "elif", "search_square", ":", "license", "=", "re", ".", "sub", "(", "r'\\[(.+)\\]'", ",", "replace_string", ",", "s", ")", "else", ":", "license", "=", "s", "return", "license", "else", ":", "print", "(", "Fore", ".", "RED", "+", "'No such license. Please check again.'", ")", ",", "print", "(", "Style", ".", "RESET_ALL", ")", ",", "sys", ".", "exit", "(", ")" ]
Actually this can be quite inefficient
def peek_many ( self , n ) : if n == 0 : return [ ] elif n == 1 : return [ self . peek ( ) ] else : items = list ( self . pop_many ( n ) ) self . update ( items ) return items
8,881
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L3377-L3397
[ "def", "read_struct", "(", "fstream", ")", ":", "line", "=", "fstream", ".", "readline", "(", ")", ".", "strip", "(", ")", "fragments", "=", "line", ".", "split", "(", "\",\"", ")", "fragments", "=", "[", "x", "for", "x", "in", "fragments", "if", "x", "is", "not", "None", "]", "partition", "=", "dict", "(", ")", "if", "not", "len", "(", "fragments", ")", ">=", "3", ":", "return", "None", "partition", "[", "\"struct\"", "]", "=", "fragments", "[", "0", "]", "partition", "[", "\"info\"", "]", "=", "fragments", "[", "1", "]", "partition", "[", "\"num_lines\"", "]", "=", "fragments", "[", "2", "]", "struct", "=", "None", "if", "partition", "is", "not", "None", "and", "partition", "[", "\"struct\"", "]", "==", "\"STRUCT\"", ":", "num_lines", "=", "int", "(", "partition", "[", "\"num_lines\"", "]", ".", "strip", "(", ")", ")", "struct", "=", "{", "}", "for", "_", "in", "range", "(", "num_lines", ")", ":", "cols", "=", "fetch_cols", "(", "fstream", ")", "struct", ".", "update", "(", "{", "cols", "[", "0", "]", ":", "cols", "[", "1", ":", "]", "}", ")", "return", "struct" ]
Pop the next item off the queue
def pop ( self , key = util_const . NoParam , default = util_const . NoParam ) : # Dictionary pop if key is specified if key is not util_const . NoParam : if default is util_const . NoParam : return ( key , self . _dict . pop ( key ) ) else : return ( key , self . _dict . pop ( key , default ) ) # Otherwise do a heap pop try : # Ammortized O(1) _heap = self . _heap _dict = self . _dict val , key = self . _heappop ( _heap ) # Remove items marked for lazy deletion as they are encountered while key not in _dict or _dict [ key ] != val : val , key = self . _heappop ( _heap ) except IndexError : if len ( _heap ) == 0 : raise IndexError ( 'queue is empty' ) else : raise del _dict [ key ] return key , val
8,882
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_dev.py#L3405-L3430
[ "def", "BuildChecks", "(", "self", ",", "request", ")", ":", "result", "=", "[", "]", "if", "request", ".", "HasField", "(", "\"start_time\"", ")", "or", "request", ".", "HasField", "(", "\"end_time\"", ")", ":", "def", "FilterTimestamp", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "HasField", "(", "\"st_mtime\"", ")", "and", "(", "file_stat", ".", "st_mtime", "<", "request", ".", "start_time", "or", "file_stat", ".", "st_mtime", ">", "request", ".", "end_time", ")", "result", ".", "append", "(", "FilterTimestamp", ")", "if", "request", ".", "HasField", "(", "\"min_file_size\"", ")", "or", "request", ".", "HasField", "(", "\"max_file_size\"", ")", ":", "def", "FilterSize", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "HasField", "(", "\"st_size\"", ")", "and", "(", "file_stat", ".", "st_size", "<", "request", ".", "min_file_size", "or", "file_stat", ".", "st_size", ">", "request", ".", "max_file_size", ")", "result", ".", "append", "(", "FilterSize", ")", "if", "request", ".", "HasField", "(", "\"perm_mode\"", ")", ":", "def", "FilterPerms", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "(", "file_stat", ".", "st_mode", "&", "request", ".", "perm_mask", ")", "!=", "request", ".", "perm_mode", "result", ".", "append", "(", "FilterPerms", ")", "if", "request", ".", "HasField", "(", "\"uid\"", ")", ":", "def", "FilterUID", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "st_uid", "!=", "request", ".", "uid", "result", ".", "append", "(", "FilterUID", ")", "if", "request", ".", "HasField", "(", "\"gid\"", ")", ":", "def", "FilterGID", "(", "file_stat", ",", "request", "=", "request", ")", ":", "return", "file_stat", ".", "st_gid", "!=", "request", ".", "gid", "result", ".", "append", "(", "FilterGID", ")", "if", "request", ".", "HasField", "(", "\"path_regex\"", ")", ":", "regex", "=", "request", ".", "path_regex", "def", "FilterPath", "(", "file_stat", ",", "regex", "=", "regex", ")", ":", "\"\"\"Suppress any filename not matching the regular expression.\"\"\"", "return", "not", "regex", ".", "Search", "(", "file_stat", ".", "pathspec", ".", "Basename", "(", ")", ")", "result", ".", "append", "(", "FilterPath", ")", "if", "request", ".", "HasField", "(", "\"data_regex\"", ")", ":", "def", "FilterData", "(", "file_stat", ",", "*", "*", "_", ")", ":", "\"\"\"Suppress files that do not match the content.\"\"\"", "return", "not", "self", ".", "TestFileContent", "(", "file_stat", ")", "result", ".", "append", "(", "FilterData", ")", "return", "result" ]
Module From Imports
def __execute_fromimport ( module , modname , import_tuples , verbose = False ) : if verbose : print ( '[UTIL_IMPORT] EXECUTING %d FROM IMPORT TUPLES' % ( len ( import_tuples ) , ) ) from_imports = __get_from_imports ( import_tuples ) for name , fromlist in from_imports : full_modname = '.' . join ( ( modname , name ) ) tmp = __import__ ( full_modname , globals ( ) , locals ( ) , fromlist = fromlist , level = 0 ) for attrname in fromlist : setattr ( module , attrname , getattr ( tmp , attrname ) ) return from_imports
8,883
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L34-L44
[ "def", "_unscramble_regressor_columns", "(", "parent_data", ",", "data", ")", ":", "matches", "=", "[", "'_power[0-9]+'", ",", "'_derivative[0-9]+'", "]", "var", "=", "OrderedDict", "(", "(", "c", ",", "deque", "(", ")", ")", "for", "c", "in", "parent_data", ".", "columns", ")", "for", "c", "in", "data", ".", "columns", ":", "col", "=", "c", "for", "m", "in", "matches", ":", "col", "=", "re", ".", "sub", "(", "m", ",", "''", ",", "col", ")", "if", "col", "==", "c", ":", "var", "[", "col", "]", ".", "appendleft", "(", "c", ")", "else", ":", "var", "[", "col", "]", ".", "append", "(", "c", ")", "unscrambled", "=", "reduce", "(", "(", "lambda", "x", ",", "y", ":", "x", "+", "y", ")", ",", "var", ".", "values", "(", ")", ")", "return", "data", "[", "[", "*", "unscrambled", "]", "]" ]
Calls the other string makers
def _initstr ( modname , imports , from_imports , inject_execstr , withheader = True ) : header = _make_module_header ( ) if withheader else '' import_str = _make_imports_str ( imports , modname ) fromimport_str = _make_fromimport_str ( from_imports , modname ) initstr = '\n' . join ( [ str_ for str_ in [ header , import_str , fromimport_str , inject_execstr , ] if len ( str_ ) > 0 ] ) return initstr
8,884
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L152-L163
[ "def", "coarse_grain", "(", "G", ",", "ncg", ")", ":", "if", "ncg", "<=", "1", ":", "return", "G", "G", "=", "numpy", ".", "asarray", "(", "G", ")", "nbin", ",", "remainder", "=", "divmod", "(", "G", ".", "shape", "[", "-", "1", "]", ",", "ncg", ")", "if", "remainder", "!=", "0", ":", "nbin", "+=", "1", "return", "numpy", ".", "transpose", "(", "[", "numpy", ".", "sum", "(", "G", "[", "...", ",", "i", ":", "i", "+", "ncg", "]", ",", "axis", "=", "-", "1", ")", "/", "G", "[", "...", ",", "i", ":", "i", "+", "ncg", "]", ".", "shape", "[", "-", "1", "]", "for", "i", "in", "numpy", ".", "arange", "(", "0", ",", "ncg", "*", "nbin", ",", "ncg", ")", "]", ")" ]
Injection and Reload String Defs
def _inject_execstr ( modname , import_tuples ) : if modname == 'utool' : # Special case import of the util_inject module injecter = 'util_inject' injecter_import = '' else : # Normal case implicit import of util_inject injecter_import = 'import utool' injecter = 'utool' injectstr_fmt = textwrap . dedent ( r''' # STARTBLOCK {injecter_import} print, rrr, profile = {injecter}.inject2(__name__, '[{modname}]') def reassign_submodule_attributes(verbose=1): """ Updates attributes in the __init__ modules with updated attributes in the submodules. """ import sys if verbose and '--quiet' not in sys.argv: print('dev reimport') # Self import import {modname} # Implicit reassignment. seen_ = set([]) for tup in IMPORT_TUPLES: if len(tup) > 2 and tup[2]: continue # dont import package names submodname, fromimports = tup[0:2] submod = getattr({modname}, submodname) for attr in dir(submod): if attr.startswith('_'): continue if attr in seen_: # This just holds off bad behavior # but it does mimic normal util_import behavior # which is good continue seen_.add(attr) setattr({modname}, attr, getattr(submod, attr)) def reload_subs(verbose=1): """ Reloads {modname} and submodules """ if verbose: print('Reloading {modname} submodules') rrr(verbose > 1) def wrap_fbrrr(mod): def fbrrr(*args, **kwargs): """ fallback reload """ if verbose > 0: print('Auto-reload (using rrr) not setup for mod=%r' % (mod,)) return fbrrr def get_rrr(mod): if hasattr(mod, 'rrr'): return mod.rrr else: return wrap_fbrrr(mod) def get_reload_subs(mod): return getattr(mod, 'reload_subs', wrap_fbrrr(mod)) {reload_body} rrr(verbose > 1) try: # hackish way of propogating up the new reloaded submodule attributes reassign_submodule_attributes(verbose=verbose) except Exception as ex: print(ex) rrrr = reload_subs # ENDBLOCK ''' ) injectstr_fmt = injectstr_fmt . replace ( '# STARTBLOCK' , '' ) injectstr_fmt = injectstr_fmt . replace ( '# ENDBLOCK' , '' ) rrrdir_fmt = ' get_reload_subs({modname})(verbose=verbose)' rrrfile_fmt = ' get_rrr({modname})(verbose > 1)' def _reload_command ( tup ) : if len ( tup ) > 2 and tup [ 2 ] is True : return rrrdir_fmt . format ( modname = tup [ 0 ] ) else : return rrrfile_fmt . format ( modname = tup [ 0 ] ) reload_body = '\n' . join ( map ( _reload_command , import_tuples ) ) . strip ( ) format_dict = { 'modname' : modname , 'reload_body' : reload_body , 'injecter' : injecter , 'injecter_import' : injecter_import , } inject_execstr = injectstr_fmt . format ( * * format_dict ) . strip ( ) return inject_execstr
8,885
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L196-L288
[ "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" ]
MAIN ENTRY POINT
def dynamic_import ( modname , import_tuples , developing = True , ignore_froms = [ ] , dump = False , ignore_startswith = [ ] , ignore_endswith = [ ] , ignore_list = [ ] , check_not_imported = True , return_initstr = False , verbose = False ) : if verbose : print ( '[UTIL_IMPORT] Running Dynamic Imports for modname=%r ' % modname ) # Get the module that will be imported into try : module = sys . modules [ modname ] except : module = __import__ ( modname ) # List of modules to be imported imports = [ tup [ 0 ] for tup in import_tuples ] # Import the modules __excecute_imports ( module , modname , imports , verbose = verbose ) # If developing do explicit import stars if developing : from_imports = __execute_fromimport_star ( module , modname , import_tuples , ignore_list = ignore_list , ignore_startswith = ignore_startswith , ignore_endswith = ignore_endswith , check_not_imported = check_not_imported , verbose = verbose ) else : from_imports = __execute_fromimport ( module , modname , import_tuples , verbose = verbose ) inject_execstr = _inject_execstr ( modname , import_tuples ) # If requested: print what the __init__ module should look like dump_requested = ( ( '--dump-%s-init' % modname ) in sys . argv or ( '--print-%s-init' % modname ) in sys . argv ) or dump overwrite_requested = ( '--update-%s-init' % modname ) in sys . argv if verbose : print ( '[UTIL_IMPORT] Finished Dynamic Imports for modname=%r ' % modname ) if dump_requested : is_main_proc = multiprocessing . current_process ( ) . name == 'MainProcess' if is_main_proc : from utool import util_str initstr = _initstr ( modname , imports , from_imports , inject_execstr ) print ( util_str . indent ( initstr ) ) # Overwrite the __init__.py file with new explicit imports if overwrite_requested : """ SeeAlso: util_inject.inject_python_code util_str.replace_between_tags """ is_main_proc = multiprocessing . current_process ( ) . name == 'MainProcess' if is_main_proc : from utool import util_str from os . path import join , exists initstr = _initstr ( modname , imports , from_imports , inject_execstr , withheader = False ) new_else = util_str . indent ( initstr ) #print(new_else) # Get path to init file so we can overwrite it init_fpath = join ( module . __path__ [ 0 ] , '__init__.py' ) print ( 'attempting to update: %r' % init_fpath ) assert exists ( init_fpath ) new_lines = [ ] editing = False updated = False #start_tag = '# <AUTOGEN_INIT>' #end_tag = '# </AUTOGEN_INIT>' with open ( init_fpath , 'r' ) as file_ : #text = file_.read() lines = file_ . readlines ( ) for line in lines : if not editing : new_lines . append ( line ) if line . strip ( ) . startswith ( '# <AUTOGEN_INIT>' ) : new_lines . append ( '\n' + new_else + '\n # </AUTOGEN_INIT>\n' ) editing = True updated = True if line . strip ( ) . startswith ( '# </AUTOGEN_INIT>' ) : editing = False # TODO: #new_text = util_str.replace_between_tags(text, new_else, start_tag, end_tag) if updated : print ( 'writing updated file: %r' % init_fpath ) new_text = '' . join ( new_lines ) with open ( init_fpath , 'w' ) as file_ : file_ . write ( new_text ) else : print ( 'no write hook for file: %r' % init_fpath ) if return_initstr : initstr = _initstr ( modname , imports , from_imports , '' , withheader = False ) return inject_execstr , initstr else : return inject_execstr
8,886
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L294-L407
[ "def", "series_fetch_by_relname", "(", "self", ",", "name", ",", "column", ")", ":", "ormclass", "=", "self", ".", "_mapped", "[", "name", "]", "# TODO: This is implemented in a not very robust way.", "id_column", "=", "re", ".", "findall", "(", "r'[A-Z][^A-Z]*'", ",", "name", ")", "[", "0", "]", "+", "'_'", "+", "'id'", "id_column", "=", "id_column", ".", "lower", "(", ")", "query", "=", "self", ".", "session", ".", "query", "(", "getattr", "(", "ormclass", ",", "id_column", ")", ",", "getattr", "(", "ormclass", ",", "column", ")", "[", "self", ".", "start_snapshot", ":", "self", ".", "end_snapshot", "]", ".", "label", "(", "column", ")", ")", ".", "filter", "(", "and_", "(", "ormclass", ".", "scn_name", "==", "self", ".", "scn_name", ",", "ormclass", ".", "temp_id", "==", "self", ".", "temp_id", ")", ")", "if", "self", ".", "version", ":", "query", "=", "query", ".", "filter", "(", "ormclass", ".", "version", "==", "self", ".", "version", ")", "df", "=", "pd", ".", "io", ".", "sql", ".", "read_sql", "(", "query", ".", "statement", ",", "self", ".", "session", ".", "bind", ",", "columns", "=", "[", "column", "]", ",", "index_col", "=", "id_column", ")", "df", ".", "index", "=", "df", ".", "index", ".", "astype", "(", "str", ")", "# change of format to fit pypsa", "df", "=", "df", "[", "column", "]", ".", "apply", "(", "pd", ".", "Series", ")", ".", "transpose", "(", ")", "try", ":", "assert", "not", "df", ".", "empty", "df", ".", "index", "=", "self", ".", "timeindex", "except", "AssertionError", ":", "print", "(", "\"No data for %s in column %s.\"", "%", "(", "name", ",", "column", ")", ")", "return", "df" ]
Just creates the string representation . Does no importing .
def make_initstr ( modname , import_tuples , verbose = False ) : imports = [ tup [ 0 ] for tup in import_tuples ] from_imports = __get_from_imports ( import_tuples ) inject_execstr = _inject_execstr ( modname , import_tuples ) return _initstr ( modname , imports , from_imports , inject_execstr )
8,887
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L410-L417
[ "def", "assignParameters", "(", "self", ",", "solution_next", ",", "DiscFac", ",", "LivPrb", ",", "CRRA", ",", "Rfree", ",", "PermGroFac", ")", ":", "self", ".", "solution_next", "=", "solution_next", "self", ".", "DiscFac", "=", "DiscFac", "self", ".", "LivPrb", "=", "LivPrb", "self", ".", "CRRA", "=", "CRRA", "self", ".", "Rfree", "=", "Rfree", "self", ".", "PermGroFac", "=", "PermGroFac" ]
Infer the import_tuples from a module_path
def make_import_tuples ( module_path , exclude_modnames = [ ] ) : from utool import util_path kwargs = dict ( private = False , full = False ) module_list = util_path . ls_modulefiles ( module_path , noext = True , * * kwargs ) package_list = util_path . ls_moduledirs ( module_path , * * kwargs ) exclude_set = set ( exclude_modnames ) module_import_tuples = [ ( modname , None ) for modname in module_list if modname not in exclude_set ] package_import_tuples = [ ( modname , None , True ) for modname in package_list if modname not in exclude_set ] import_tuples = ( module_import_tuples + package_import_tuples ) return import_tuples
8,888
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/util_importer.py#L420-L432
[ "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" ]
Returns a directory which should be writable for any application
def get_resource_dir ( ) : #resource_prefix = '~' if WIN32 : dpath_ = '~/AppData/Roaming' elif LINUX : dpath_ = '~/.config' elif DARWIN : dpath_ = '~/Library/Application Support' else : raise AssertionError ( 'unknown os' ) dpath = normpath ( expanduser ( dpath_ ) ) return dpath
8,889
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/_internal/meta_util_cplat.py#L16-L30
[ "def", "add_reference", "(", "self", ",", "source", ",", "target", ",", "*", "*", "kwargs", ")", ":", "# Tweak keyword arguments for addReference", "addRef_kw", "=", "kwargs", ".", "copy", "(", ")", "addRef_kw", ".", "setdefault", "(", "\"referenceClass\"", ",", "self", ".", "referenceClass", ")", "if", "\"schema\"", "in", "addRef_kw", ":", "del", "addRef_kw", "[", "\"schema\"", "]", "uid", "=", "api", ".", "get_uid", "(", "target", ")", "rc", "=", "api", ".", "get_tool", "(", "\"reference_catalog\"", ")", "# throws IndexError if uid is invalid", "rc", ".", "addReference", "(", "source", ",", "uid", ",", "self", ".", "relationship", ",", "*", "*", "addRef_kw", ")", "# link the version of the reference", "self", ".", "link_version", "(", "source", ",", "target", ")" ]
More generic interface to load data
def load_data ( fpath , * * kwargs ) : ext = splitext ( fpath ) [ 1 ] if ext in [ '.pickle' , '.cPkl' , '.pkl' ] : return load_cPkl ( fpath , * * kwargs ) elif ext in [ '.json' ] : return load_json ( fpath , * * kwargs ) elif ext in [ '.hdf5' ] : return load_hdf5 ( fpath , * * kwargs ) elif ext in [ '.txt' ] : return load_text ( fpath , * * kwargs ) elif HAS_NUMPY and ext in [ '.npz' , '.npy' ] : return load_numpy ( fpath , * * kwargs ) else : assert False , 'unknown ext=%r for fpath=%r' % ( ext , fpath )
8,890
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L32-L46
[ "def", "move_right", "(", "self", ",", "keep_anchor", "=", "False", ",", "nb_chars", "=", "1", ")", ":", "text_cursor", "=", "self", ".", "_editor", ".", "textCursor", "(", ")", "text_cursor", ".", "movePosition", "(", "text_cursor", ".", "Right", ",", "text_cursor", ".", "KeepAnchor", "if", "keep_anchor", "else", "text_cursor", ".", "MoveAnchor", ",", "nb_chars", ")", "self", ".", "_editor", ".", "setTextCursor", "(", "text_cursor", ")" ]
More generic interface to write data
def save_data ( fpath , data , * * kwargs ) : ext = splitext ( fpath ) [ 1 ] if ext in [ '.pickle' , '.cPkl' , '.pkl' ] : return save_cPkl ( fpath , data , * * kwargs ) elif ext in [ '.json' ] : return save_json ( fpath , data , * * kwargs ) elif ext in [ '.hdf5' ] : return save_hdf5 ( fpath , data , * * kwargs ) elif ext in [ '.txt' ] : return save_text ( fpath , * * kwargs ) elif HAS_NUMPY and ext in [ '.npz' , '.npy' ] : return save_numpy ( fpath , data , * * kwargs ) else : assert False , 'unknown ext=%r for fpath=%r' % ( ext , fpath )
8,891
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L49-L63
[ "def", "Nu_vertical_cylinder", "(", "Pr", ",", "Gr", ",", "L", "=", "None", ",", "D", "=", "None", ",", "Method", "=", "None", ",", "AvailableMethods", "=", "False", ")", ":", "def", "list_methods", "(", ")", ":", "methods", "=", "[", "]", "for", "key", ",", "values", "in", "vertical_cylinder_correlations", ".", "items", "(", ")", ":", "if", "values", "[", "4", "]", "or", "all", "(", "(", "L", ",", "D", ")", ")", ":", "methods", ".", "append", "(", "key", ")", "if", "'Popiel & Churchill'", "in", "methods", ":", "methods", ".", "remove", "(", "'Popiel & Churchill'", ")", "methods", ".", "insert", "(", "0", ",", "'Popiel & Churchill'", ")", "elif", "'McAdams, Weiss & Saunders'", "in", "methods", ":", "methods", ".", "remove", "(", "'McAdams, Weiss & Saunders'", ")", "methods", ".", "insert", "(", "0", ",", "'McAdams, Weiss & Saunders'", ")", "return", "methods", "if", "AvailableMethods", ":", "return", "list_methods", "(", ")", "if", "not", "Method", ":", "Method", "=", "list_methods", "(", ")", "[", "0", "]", "if", "Method", "in", "vertical_cylinder_correlations", ":", "if", "vertical_cylinder_correlations", "[", "Method", "]", "[", "4", "]", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ")", "else", ":", "return", "vertical_cylinder_correlations", "[", "Method", "]", "[", "0", "]", "(", "Pr", "=", "Pr", ",", "Gr", "=", "Gr", ",", "L", "=", "L", ",", "D", "=", "D", ")", "else", ":", "raise", "Exception", "(", "\"Correlation name not recognized; see the \"", "\"documentation for the available options.\"", ")" ]
Writes text to a file . Automatically encodes text as utf8 .
def write_to ( fpath , to_write , aslines = False , verbose = None , onlyifdiff = False , mode = 'w' , n = None ) : if onlyifdiff : import utool as ut if ut . hashstr ( read_from ( fpath ) ) == ut . hashstr ( to_write ) : print ( '[util_io] * no difference' ) return verbose = _rectify_verb_write ( verbose ) if verbose : # n = None if verbose > 1 else 2 # print('[util_io] * Writing to text file: %r ' % util_path.tail(fpath, n=n)) print ( '[util_io] * Writing to text file: {}' . format ( fpath ) ) backup = False and exists ( fpath ) if backup : util_path . copy ( fpath , fpath + '.backup' ) if not isinstance ( fpath , six . string_types ) : # Assuming a file object with a name attribute # Should just read from the file fpath = fpath . name with open ( fpath , mode ) as file_ : if aslines : file_ . writelines ( to_write ) else : # Ensure python2 writes in bytes if six . PY2 : if isinstance ( to_write , unicode ) : # NOQA to_write = to_write . encode ( 'utf8' ) try : file_ . write ( to_write ) except UnicodeEncodeError as ex : start = max ( ex . args [ 2 ] - 10 , 0 ) end = ex . args [ 3 ] + 10 context = to_write [ start : end ] print ( repr ( context ) ) print ( context ) from utool import util_dbg util_dbg . printex ( ex , keys = [ ( type , 'to_write' ) ] ) file_ . close ( ) if backup : # restore util_path . copy ( fpath + '.backup' , fpath ) # import utool # utool.embed() raise
8,892
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L82-L161
[ "def", "leave_moderator", "(", "self", ",", "subreddit", ")", ":", "self", ".", "evict", "(", "self", ".", "config", "[", "'my_mod_subreddits'", "]", ")", "return", "self", ".", "_leave_status", "(", "subreddit", ",", "self", ".", "config", "[", "'leavemoderator'", "]", ")" ]
r Reads text from a file . Automatically returns utf8 .
def read_from ( fpath , verbose = None , aslines = False , strict = True , n = None , errors = 'replace' ) : if n is None : n = __READ_TAIL_N__ verbose = _rectify_verb_read ( verbose ) if verbose : print ( '[util_io] * Reading text file: %r ' % util_path . tail ( fpath , n = n ) ) try : if not util_path . checkpath ( fpath , verbose = verbose , n = n ) : raise IOError ( '[io] * FILE DOES NOT EXIST!' ) #with open(fpath, 'r') as file_: with open ( fpath , 'rb' ) as file_ : if aslines : #text = file_.readlines() if six . PY2 : # python2 writes in bytes, so read as bytes then convert to # utf8 text = [ line . decode ( 'utf8' , errors = errors ) for line in file_ . readlines ( ) ] else : text = [ line . decode ( 'utf8' , errors = errors ) for line in file_ . readlines ( ) ] #text = file_.readlines() else : # text = file_.read() if six . PY2 : text = file_ . read ( ) . decode ( 'utf8' , errors = errors ) else : #text = file_.read() text = file_ . read ( ) . decode ( 'utf8' , errors = errors ) return text except IOError as ex : from utool import util_dbg if verbose or strict : util_dbg . printex ( ex , ' * Error reading fpath=%r' % util_path . tail ( fpath , n = n ) , '[io]' ) if strict : raise
8,893
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L164-L216
[ "def", "detach_session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "not", "None", ":", "self", ".", "_session", ".", "unsubscribe", "(", "self", ")", "self", ".", "_session", "=", "None" ]
Saves data to a pickled file with optional verbosity
def save_cPkl ( fpath , data , verbose = None , n = None ) : verbose = _rectify_verb_write ( verbose ) if verbose : print ( '[util_io] * save_cPkl(%r, data)' % ( util_path . tail ( fpath , n = n ) , ) ) with open ( fpath , 'wb' ) as file_ : # Use protocol 2 to support python2 and 3 pickle . dump ( data , file_ , protocol = 2 )
8,894
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L249-L256
[ "def", "_intersection", "(", "self", ",", "keys", ",", "rows", ")", ":", "# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.", "if", "not", "keys", ":", "return", "rows", "ret", "=", "list", "(", ")", "for", "row", "in", "rows", ":", "start_date", "=", "row", "[", "self", ".", "_key_start_date", "]", "end_date", "=", "row", "[", "self", ".", "_key_end_date", "]", "for", "key_start_date", ",", "key_end_date", "in", "keys", ":", "start_date", ",", "end_date", "=", "Type2JoinHelper", ".", "_intersect", "(", "start_date", ",", "end_date", ",", "row", "[", "key_start_date", "]", ",", "row", "[", "key_end_date", "]", ")", "if", "not", "start_date", ":", "break", "if", "key_start_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_start_date", "]", "if", "key_end_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_end_date", "]", "if", "start_date", ":", "row", "[", "self", ".", "_key_start_date", "]", "=", "start_date", "row", "[", "self", ".", "_key_end_date", "]", "=", "end_date", "ret", ".", "append", "(", "row", ")", "return", "ret" ]
Loads a pickled file with optional verbosity . Aims for compatibility between python2 and python3 .
def load_cPkl ( fpath , verbose = None , n = None ) : verbose = _rectify_verb_read ( verbose ) if verbose : print ( '[util_io] * load_cPkl(%r)' % ( util_path . tail ( fpath , n = n ) , ) ) try : with open ( fpath , 'rb' ) as file_ : data = pickle . load ( file_ ) except UnicodeDecodeError : if six . PY3 : # try to open python2 pickle with open ( fpath , 'rb' ) as file_ : data = pickle . load ( file_ , encoding = 'latin1' ) else : raise except ValueError as ex : if six . PY2 : if ex . message == 'unsupported pickle protocol: 4' : raise ValueError ( 'unsupported Python3 pickle protocol 4 ' 'in Python2 for fpath=%r' % ( fpath , ) ) else : raise else : raise return data
8,895
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L259-L354
[ "def", "get_unused_list_annotation_values", "(", "graph", ")", "->", "Mapping", "[", "str", ",", "Set", "[", "str", "]", "]", ":", "result", "=", "{", "}", "for", "annotation", ",", "values", "in", "graph", ".", "annotation_list", ".", "items", "(", ")", ":", "used_values", "=", "get_annotation_values", "(", "graph", ",", "annotation", ")", "if", "len", "(", "used_values", ")", "==", "len", "(", "values", ")", ":", "# all values have been used", "continue", "result", "[", "annotation", "]", "=", "set", "(", "values", ")", "-", "used_values", "return", "result" ]
r Restricted save of data using hdf5 . Can only save ndarrays and dicts of ndarrays .
def save_hdf5 ( fpath , data , verbose = None , compression = 'lzf' ) : import h5py verbose = _rectify_verb_write ( verbose ) if verbose : print ( '[util_io] * save_hdf5(%r, data)' % ( util_path . tail ( fpath ) , ) ) if verbose > 1 : if isinstance ( data , dict ) : print ( '[util_io] ... shapes=%r' % ( [ val . shape for val in data . values ( ) ] , ) ) else : print ( '[util_io] ... shape=%r' % ( data . shape , ) ) chunks = True # True enables auto-chunking fname = basename ( fpath ) # check for parallel hdf5 #have_mpi = h5py.h5.get_config().mpi #if have_mpi: # import mpi4py # h5kw = dict(driver='mpio', comm=mpi4py.MPI.COMM_WORLD) # # cant use compression with mpi # #ValueError: Unable to create dataset (Parallel i/o does not support filters yet) #else: h5kw = { } if isinstance ( data , dict ) : array_data = { key : val for key , val in data . items ( ) if isinstance ( val , ( list , np . ndarray ) ) } attr_data = { key : val for key , val in data . items ( ) if key not in array_data } #assert all([ # isinstance(vals, np.ndarray) # for vals in six.itervalues(data) #]), ('can only save dicts as ndarrays') # file_ = h5py.File(fpath, 'w', **h5kw) with h5py . File ( fpath , mode = 'w' , * * h5kw ) as file_ : grp = file_ . create_group ( fname ) for key , val in six . iteritems ( array_data ) : val = np . asarray ( val ) dset = grp . create_dataset ( key , val . shape , val . dtype , chunks = chunks , compression = compression ) dset [ ... ] = val for key , val in six . iteritems ( attr_data ) : grp . attrs [ key ] = val else : assert isinstance ( data , np . ndarray ) shape = data . shape dtype = data . dtype #if verbose or (verbose is None and __PRINT_WRITES__): # print('[util_io] * save_hdf5(%r, data)' % (util_path.tail(fpath),)) # file_ = h5py.File(fpath, 'w', **h5kw) with h5py . File ( fpath , mode = 'w' , * * h5kw ) as file_ : #file_.create_dataset( # fname, shape, dtype, chunks=chunks, compression=compression, # data=data) dset = file_ . create_dataset ( fname , shape , dtype , chunks = chunks , compression = compression ) dset [ ... ] = data
8,896
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L398-L612
[ "def", "nearest_tile_to_edge_using_tiles", "(", "tile_ids", ",", "edge_coord", ")", ":", "for", "tile_id", "in", "tile_ids", ":", "if", "edge_coord", "-", "tile_id_to_coord", "(", "tile_id", ")", "in", "_tile_edge_offsets", ".", "keys", "(", ")", ":", "return", "tile_id", "logging", ".", "critical", "(", "'Did not find a tile touching edge={}'", ".", "format", "(", "edge_coord", ")", ")" ]
sudo pip install numexpr sudo pip install tables
def save_pytables ( fpath , data , verbose = False ) : import tables #from os.path import basename #fname = basename(fpath) #shape = data.shape #dtype = data.dtype #file_ = tables.open_file(fpath) verbose = _rectify_verb_write ( verbose ) if verbose : print ( '[util_io] * save_pytables(%r, data)' % ( util_path . tail ( fpath ) , ) ) with tables . open_file ( fpath , 'w' ) as file_ : atom = tables . Atom . from_dtype ( data . dtype ) filters = tables . Filters ( complib = 'blosc' , complevel = 5 ) dset = file_ . createCArray ( file_ . root , 'data' , atom , data . shape , filters = filters ) # save w/o compressive filter #dset = file_.createCArray(file_.root, 'all_data', atom, all_data.shape) dset [ : ] = data
8,897
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_io.py#L648-L693
[ "def", "face_index", "(", "vertices", ")", ":", "new_verts", "=", "[", "]", "face_indices", "=", "[", "]", "for", "wall", "in", "vertices", ":", "face_wall", "=", "[", "]", "for", "vert", "in", "wall", ":", "if", "new_verts", ":", "if", "not", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ".", "any", "(", ")", ":", "new_verts", ".", "append", "(", "vert", ")", "else", ":", "new_verts", ".", "append", "(", "vert", ")", "face_index", "=", "np", ".", "where", "(", "np", ".", "isclose", "(", "vert", ",", "new_verts", ")", ".", "all", "(", "axis", "=", "1", ")", ")", "[", "0", "]", "[", "0", "]", "face_wall", ".", "append", "(", "face_index", ")", "face_indices", ".", "append", "(", "face_wall", ")", "return", "np", ".", "array", "(", "new_verts", ")", ",", "np", ".", "array", "(", "face_indices", ")" ]
r simple webserver that echos its arguments
def start_simple_webserver ( domain = None , port = 5832 ) : import tornado . ioloop import tornado . web import tornado . httpserver import tornado . wsgi import flask app = flask . Flask ( '__simple__' ) @ app . route ( '/' , methods = [ 'GET' , 'POST' , 'DELETE' , 'PUT' ] ) def echo_args ( * args , * * kwargs ) : from flask import request print ( 'Simple server was pinged' ) print ( 'args = %r' % ( args , ) ) print ( 'kwargs = %r' % ( kwargs , ) ) print ( 'request.args = %r' % ( request . args , ) ) print ( 'request.form = %r' % ( request . form , ) ) return '' if domain is None : domain = get_localhost ( ) app . server_domain = domain app . server_port = port app . server_url = 'http://%s:%s' % ( app . server_domain , app . server_port ) print ( 'app.server_url = %s' % ( app . server_url , ) ) http_server = tornado . httpserver . HTTPServer ( tornado . wsgi . WSGIContainer ( app ) ) http_server . listen ( app . server_port ) tornado . ioloop . IOLoop . instance ( ) . start ( )
8,898
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_web.py#L66-L110
[ "def", "setupTable_name", "(", "self", ")", ":", "if", "\"name\"", "not", "in", "self", ".", "tables", ":", "return", "font", "=", "self", ".", "ufo", "self", ".", "otf", "[", "\"name\"", "]", "=", "name", "=", "newTable", "(", "\"name\"", ")", "name", ".", "names", "=", "[", "]", "# Set name records from font.info.openTypeNameRecords", "for", "nameRecord", "in", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameRecords\"", ")", ":", "nameId", "=", "nameRecord", "[", "\"nameID\"", "]", "platformId", "=", "nameRecord", "[", "\"platformID\"", "]", "platEncId", "=", "nameRecord", "[", "\"encodingID\"", "]", "langId", "=", "nameRecord", "[", "\"languageID\"", "]", "# on Python 2, plistLib (used by ufoLib) returns unicode strings", "# only when plist data contain non-ascii characters, and returns", "# ascii-encoded bytes when it can. On the other hand, fontTools's", "# name table `setName` method wants unicode strings, so we must", "# decode them first", "nameVal", "=", "tounicode", "(", "nameRecord", "[", "\"string\"", "]", ",", "encoding", "=", "'ascii'", ")", "name", ".", "setName", "(", "nameVal", ",", "nameId", ",", "platformId", ",", "platEncId", ",", "langId", ")", "# Build name records", "familyName", "=", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"styleMapFamilyName\"", ")", "styleName", "=", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"styleMapStyleName\"", ")", ".", "title", "(", ")", "preferredFamilyName", "=", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNamePreferredFamilyName\"", ")", "preferredSubfamilyName", "=", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNamePreferredSubfamilyName\"", ")", "fullName", "=", "\"%s %s\"", "%", "(", "preferredFamilyName", ",", "preferredSubfamilyName", ")", "nameVals", "=", "{", "0", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"copyright\"", ")", ",", "1", ":", "familyName", ",", "2", ":", "styleName", ",", "3", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameUniqueID\"", ")", ",", "4", ":", "fullName", ",", "5", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameVersion\"", ")", ",", "6", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"postscriptFontName\"", ")", ",", "7", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"trademark\"", ")", ",", "8", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameManufacturer\"", ")", ",", "9", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameDesigner\"", ")", ",", "10", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameDescription\"", ")", ",", "11", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameManufacturerURL\"", ")", ",", "12", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameDesignerURL\"", ")", ",", "13", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameLicense\"", ")", ",", "14", ":", "getAttrWithFallback", "(", "font", ".", "info", ",", "\"openTypeNameLicenseURL\"", ")", ",", "16", ":", "preferredFamilyName", ",", "17", ":", "preferredSubfamilyName", ",", "}", "# don't add typographic names if they are the same as the legacy ones", "if", "nameVals", "[", "1", "]", "==", "nameVals", "[", "16", "]", ":", "del", "nameVals", "[", "16", "]", "if", "nameVals", "[", "2", "]", "==", "nameVals", "[", "17", "]", ":", "del", "nameVals", "[", "17", "]", "# postscript font name", "if", "nameVals", "[", "6", "]", ":", "nameVals", "[", "6", "]", "=", "normalizeStringForPostscript", "(", "nameVals", "[", "6", "]", ")", "for", "nameId", "in", "sorted", "(", "nameVals", ".", "keys", "(", ")", ")", ":", "nameVal", "=", "nameVals", "[", "nameId", "]", "if", "not", "nameVal", ":", "continue", "nameVal", "=", "tounicode", "(", "nameVal", ",", "encoding", "=", "'ascii'", ")", "platformId", "=", "3", "platEncId", "=", "10", "if", "_isNonBMP", "(", "nameVal", ")", "else", "1", "langId", "=", "0x409", "# Set built name record if not set yet", "if", "name", ".", "getName", "(", "nameId", ",", "platformId", ",", "platEncId", ",", "langId", ")", ":", "continue", "name", ".", "setName", "(", "nameVal", ",", "nameId", ",", "platformId", ",", "platEncId", ",", "langId", ")" ]
makes a temporary html rendering
def render_html ( html_str ) : import utool as ut from os . path import abspath import webbrowser try : html_str = html_str . decode ( 'utf8' ) except Exception : pass html_dpath = ut . ensure_app_resource_dir ( 'utool' , 'temp_html' ) fpath = abspath ( ut . unixjoin ( html_dpath , 'temp.html' ) ) url = 'file://' + fpath ut . writeto ( fpath , html_str ) webbrowser . open ( url )
8,899
https://github.com/Erotemic/utool/blob/3b27e1f4e6e6fb23cd8744af7b7195b57d99e03a/utool/util_web.py#L113-L130
[ "def", "neurite_centre_of_mass", "(", "neurite", ")", ":", "centre_of_mass", "=", "np", ".", "zeros", "(", "3", ")", "total_volume", "=", "0", "seg_vol", "=", "np", ".", "array", "(", "map", "(", "mm", ".", "segment_volume", ",", "nm", ".", "iter_segments", "(", "neurite", ")", ")", ")", "seg_centre_of_mass", "=", "np", ".", "array", "(", "map", "(", "segment_centre_of_mass", ",", "nm", ".", "iter_segments", "(", "neurite", ")", ")", ")", "# multiply array of scalars with array of arrays", "# http://stackoverflow.com/questions/5795700/multiply-numpy-array-of-scalars-by-array-of-vectors", "seg_centre_of_mass", "=", "seg_centre_of_mass", "*", "seg_vol", "[", ":", ",", "np", ".", "newaxis", "]", "centre_of_mass", "=", "np", ".", "sum", "(", "seg_centre_of_mass", ",", "axis", "=", "0", ")", "total_volume", "=", "np", ".", "sum", "(", "seg_vol", ")", "return", "centre_of_mass", "/", "total_volume" ]