idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
59,100 | def initialize ( self ) : self . time . update ( self . components . initial_time ( ) ) self . time . stage = 'Initialization' super ( Model , self ) . initialize ( ) | Initializes the simulation model |
59,101 | def _format_return_timestamps ( self , return_timestamps = None ) : if return_timestamps is None : return_timestamps_array = np . arange ( self . components . initial_time ( ) , self . components . final_time ( ) + self . components . saveper ( ) , self . components . saveper ( ) , dtype = np . float64 ) elif inspect . isclass ( range ) and isinstance ( return_timestamps , range ) : return_timestamps_array = np . array ( return_timestamps , ndmin = 1 ) elif isinstance ( return_timestamps , ( list , int , float , np . ndarray ) ) : return_timestamps_array = np . array ( return_timestamps , ndmin = 1 ) elif isinstance ( return_timestamps , _pd . Series ) : return_timestamps_array = return_timestamps . as_matrix ( ) else : raise TypeError ( '`return_timestamps` expects a list, array, pandas Series, ' 'or numeric value' ) return return_timestamps_array | Format the passed in return timestamps value as a numpy array . If no value is passed build up array of timestamps based upon model start and end times and the saveper value . |
59,102 | def run ( self , params = None , return_columns = None , return_timestamps = None , initial_condition = 'original' , reload = False ) : if reload : self . reload ( ) if params : self . set_components ( params ) self . set_initial_condition ( initial_condition ) return_timestamps = self . _format_return_timestamps ( return_timestamps ) t_series = self . _build_euler_timeseries ( return_timestamps ) if return_columns is None : return_columns = self . _default_return_columns ( ) self . time . stage = 'Run' self . clear_caches ( ) capture_elements , return_addresses = utils . get_return_elements ( return_columns , self . components . _namespace , self . components . _subscript_dict ) res = self . _integrate ( t_series , capture_elements , return_timestamps ) return_df = utils . make_flat_df ( res , return_addresses ) return_df . index = return_timestamps return return_df | Simulate the model s behavior over time . Return a pandas dataframe with timestamps as rows model elements as columns . |
59,103 | def _default_return_columns ( self ) : return_columns = [ ] parsed_expr = [ ] for key , value in self . components . _namespace . items ( ) : if hasattr ( self . components , value ) : sig = signature ( getattr ( self . components , value ) ) if len ( set ( sig . parameters ) - { 'args' } ) == 0 : expr = self . components . _namespace [ key ] if not expr in parsed_expr : return_columns . append ( key ) parsed_expr . append ( expr ) return return_columns | Return a list of the model elements that does not include lookup functions or other functions that take parameters . |
59,104 | def set_initial_condition ( self , initial_condition ) : if isinstance ( initial_condition , tuple ) : self . set_state ( * initial_condition ) elif isinstance ( initial_condition , str ) : if initial_condition . lower ( ) in [ 'original' , 'o' ] : self . initialize ( ) elif initial_condition . lower ( ) in [ 'current' , 'c' ] : pass else : raise ValueError ( 'Valid initial condition strings include: \n' + ' "original"/"o", \n' + ' "current"/"c"' ) else : raise TypeError ( 'Check documentation for valid entries' ) | Set the initial conditions of the integration . |
59,105 | def _euler_step ( self , dt ) : self . state = self . state + self . ddt ( ) * dt | Performs a single step in the euler integration updating stateful components |
59,106 | def _integrate ( self , time_steps , capture_elements , return_timestamps ) : outputs = [ ] for t2 in time_steps [ 1 : ] : if self . time ( ) in return_timestamps : outputs . append ( { key : getattr ( self . components , key ) ( ) for key in capture_elements } ) self . _euler_step ( t2 - self . time ( ) ) self . time . update ( t2 ) if self . time ( ) in return_timestamps : outputs . append ( { key : getattr ( self . components , key ) ( ) for key in capture_elements } ) return outputs | Performs euler integration |
59,107 | def merge_partial_elements ( element_list ) : outs = dict ( ) for element in element_list : if element [ 'py_expr' ] != "None" : name = element [ 'py_name' ] if name not in outs : eqn = element [ 'expr' ] if 'expr' in element else element [ 'eqn' ] outs [ name ] = { 'py_name' : element [ 'py_name' ] , 'real_name' : element [ 'real_name' ] , 'doc' : element [ 'doc' ] , 'py_expr' : [ element [ 'py_expr' ] ] , 'unit' : element [ 'unit' ] , 'subs' : [ element [ 'subs' ] ] , 'lims' : element [ 'lims' ] , 'eqn' : eqn , 'kind' : element [ 'kind' ] , 'arguments' : element [ 'arguments' ] } else : outs [ name ] [ 'doc' ] = outs [ name ] [ 'doc' ] or element [ 'doc' ] outs [ name ] [ 'unit' ] = outs [ name ] [ 'unit' ] or element [ 'unit' ] outs [ name ] [ 'lims' ] = outs [ name ] [ 'lims' ] or element [ 'lims' ] outs [ name ] [ 'eqn' ] = outs [ name ] [ 'eqn' ] or element [ 'eqn' ] outs [ name ] [ 'py_expr' ] += [ element [ 'py_expr' ] ] outs [ name ] [ 'subs' ] += [ element [ 'subs' ] ] outs [ name ] [ 'arguments' ] = element [ 'arguments' ] return list ( outs . values ( ) ) | merges model elements which collectively all define the model component mostly for multidimensional subscripts |
59,108 | def add_n_delay ( delay_input , delay_time , initial_value , order , subs , subscript_dict ) : stateful = { 'py_name' : utils . make_python_identifier ( '_delay_%s_%s_%s_%s' % ( delay_input , delay_time , initial_value , order ) ) [ 0 ] , 'real_name' : 'Delay of %s' % delay_input , 'doc' : 'Delay time: %s \n Delay initial value %s \n Delay order %s' % ( delay_time , initial_value , order ) , 'py_expr' : 'functions.Delay(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( delay_input , delay_time , initial_value , order ) , 'unit' : 'None' , 'lims' : 'None' , 'eqn' : 'None' , 'subs' : '' , 'kind' : 'stateful' , 'arguments' : '' } return "%s()" % stateful [ 'py_name' ] , [ stateful ] | Creates code to instantiate a stateful Delay object and provides reference to that object s output . |
59,109 | def add_n_smooth ( smooth_input , smooth_time , initial_value , order , subs , subscript_dict ) : stateful = { 'py_name' : utils . make_python_identifier ( '_smooth_%s_%s_%s_%s' % ( smooth_input , smooth_time , initial_value , order ) ) [ 0 ] , 'real_name' : 'Smooth of %s' % smooth_input , 'doc' : 'Smooth time: %s \n Smooth initial value %s \n Smooth order %s' % ( smooth_time , initial_value , order ) , 'py_expr' : 'functions.Smooth(lambda: %s, lambda: %s, lambda: %s, lambda: %s)' % ( smooth_input , smooth_time , initial_value , order ) , 'unit' : 'None' , 'lims' : 'None' , 'eqn' : 'None' , 'subs' : '' , 'kind' : 'stateful' , 'arguments' : '' } return "%s()" % stateful [ 'py_name' ] , [ stateful ] | Constructs stock and flow chains that implement the calculation of a smoothing function . |
59,110 | def add_initial ( initial_input ) : stateful = { 'py_name' : utils . make_python_identifier ( '_initial_%s' % initial_input ) [ 0 ] , 'real_name' : 'Smooth of %s' % initial_input , 'doc' : 'Returns the value taken on during the initialization phase' , 'py_expr' : 'functions.Initial(lambda: %s)' % ( initial_input ) , 'unit' : 'None' , 'lims' : 'None' , 'eqn' : 'None' , 'subs' : '' , 'kind' : 'stateful' , 'arguments' : '' } return "%s()" % stateful [ 'py_name' ] , [ stateful ] | Constructs a stateful object for handling vensim s Initial functionality |
59,111 | def add_macro ( macro_name , filename , arg_names , arg_vals ) : func_args = '{ %s }' % ', ' . join ( [ "'%s': lambda: %s" % ( key , val ) for key , val in zip ( arg_names , arg_vals ) ] ) stateful = { 'py_name' : '_macro_' + macro_name + '_' + '_' . join ( [ utils . make_python_identifier ( f ) [ 0 ] for f in arg_vals ] ) , 'real_name' : 'Macro Instantiation of ' + macro_name , 'doc' : 'Instantiates the Macro' , 'py_expr' : "functions.Macro('%s', %s, '%s', time_initialization=lambda: __data['time'])" % ( filename , func_args , macro_name ) , 'unit' : 'None' , 'lims' : 'None' , 'eqn' : 'None' , 'subs' : '' , 'kind' : 'stateful' , 'arguments' : '' } return "%s()" % stateful [ 'py_name' ] , [ stateful ] | Constructs a stateful object instantiating a Macro |
59,112 | def add_incomplete ( var_name , dependencies ) : warnings . warn ( '%s has no equation specified' % var_name , SyntaxWarning , stacklevel = 2 ) return "functions.incomplete(%s)" % ', ' . join ( dependencies [ 1 : ] ) , [ ] | Incomplete functions don t really need to be builders as they add no new real structure but it s helpful to have a function in which we can raise a warning about the incomplete equation at translate time . |
59,113 | def get_model_elements ( model_str ) : model_structure_grammar = _include_common_grammar ( r ) parser = parsimonious . Grammar ( model_structure_grammar ) tree = parser . parse ( model_str ) class ModelParser ( parsimonious . NodeVisitor ) : def __init__ ( self , ast ) : self . entries = [ ] self . visit ( ast ) def visit_entry ( self , n , vc ) : units , lims = parse_units ( vc [ 2 ] . strip ( ) ) self . entries . append ( { 'eqn' : vc [ 0 ] . strip ( ) , 'unit' : units , 'lims' : str ( lims ) , 'doc' : vc [ 4 ] . strip ( ) , 'kind' : 'entry' } ) def visit_section ( self , n , vc ) : if vc [ 2 ] . strip ( ) != "Simulation Control Parameters" : self . entries . append ( { 'eqn' : '' , 'unit' : '' , 'lims' : '' , 'doc' : vc [ 2 ] . strip ( ) , 'kind' : 'section' } ) def generic_visit ( self , n , vc ) : return '' . join ( filter ( None , vc ) ) or n . text or '' return ModelParser ( tree ) . entries | Takes in a string representing model text and splits it into elements |
59,114 | def get_equation_components ( equation_str ) : component_structure_grammar = _include_common_grammar ( r ) equation_str = equation_str . replace ( '\\t' , ' ' ) equation_str = re . sub ( r"\s+" , ' ' , equation_str ) parser = parsimonious . Grammar ( component_structure_grammar ) tree = parser . parse ( equation_str ) class ComponentParser ( parsimonious . NodeVisitor ) : def __init__ ( self , ast ) : self . subscripts = [ ] self . real_name = None self . expression = None self . kind = None self . visit ( ast ) def visit_subscript_definition ( self , n , vc ) : self . kind = 'subdef' def visit_lookup_definition ( self , n , vc ) : self . kind = 'lookup' def visit_component ( self , n , vc ) : self . kind = 'component' def visit_name ( self , n , vc ) : ( name , ) = vc self . real_name = name . strip ( ) def visit_subscript ( self , n , vc ) : ( subscript , ) = vc self . subscripts . append ( subscript . strip ( ) ) def visit_expression ( self , n , vc ) : self . expression = n . text . strip ( ) def generic_visit ( self , n , vc ) : return '' . join ( filter ( None , vc ) ) or n . text def visit__ ( self , n , vc ) : return ' ' parse_object = ComponentParser ( tree ) return { 'real_name' : parse_object . real_name , 'subs' : parse_object . subscripts , 'expr' : parse_object . expression , 'kind' : parse_object . kind } | Breaks down a string representing only the equation part of a model element . Recognizes the various types of model elements that may exist and identifies them . |
59,115 | def parse_units ( units_str ) : if not len ( units_str ) : return units_str , ( None , None ) if units_str [ - 1 ] == ']' : units , lims = units_str . rsplit ( '[' ) else : units = units_str lims = '?, ?]' lims = tuple ( [ float ( x ) if x . strip ( ) != '?' else None for x in lims . strip ( ']' ) . split ( ',' ) ] ) return units . strip ( ) , lims | Extract and parse the units Extract the bounds over which the expression is assumed to apply . |
59,116 | def parse_lookup_expression ( element ) : lookup_grammar = r parser = parsimonious . Grammar ( lookup_grammar ) tree = parser . parse ( element [ 'expr' ] ) class LookupParser ( parsimonious . NodeVisitor ) : def __init__ ( self , ast ) : self . translation = "" self . new_structure = [ ] self . visit ( ast ) def visit__ ( self , n , vc ) : return '' def visit_lookup ( self , n , vc ) : pairs = max ( vc , key = len ) mixed_list = pairs . replace ( '(' , '' ) . replace ( ')' , '' ) . split ( ',' ) xs = mixed_list [ : : 2 ] ys = mixed_list [ 1 : : 2 ] string = "functions.lookup(x, [%(xs)s], [%(ys)s])" % { 'xs' : ',' . join ( xs ) , 'ys' : ',' . join ( ys ) } self . translation = string def generic_visit ( self , n , vc ) : return '' . join ( filter ( None , vc ) ) or n . text parse_object = LookupParser ( tree ) return { 'py_expr' : parse_object . translation , 'arguments' : 'x' } | This syntax parses lookups that are defined with their own element |
59,117 | def dict_find ( in_dict , value ) : return list ( in_dict . keys ( ) ) [ list ( in_dict . values ( ) ) . index ( value ) ] | Helper function for looking up directory keys by their values . This isn t robust to repeated values |
59,118 | def find_subscript_name ( subscript_dict , element ) : if element in subscript_dict . keys ( ) : return element for name , elements in subscript_dict . items ( ) : if element in elements : return name | Given a subscript dictionary and a member of a subscript family return the first key of which the member is within the value list . If element is already a subscript name return that |
59,119 | def make_coord_dict ( subs , subscript_dict , terse = True ) : sub_elems_list = [ y for x in subscript_dict . values ( ) for y in x ] coordinates = { } for sub in subs : if sub in sub_elems_list : name = find_subscript_name ( subscript_dict , sub ) coordinates [ name ] = [ sub ] elif not terse : coordinates [ sub ] = subscript_dict [ sub ] return coordinates | This is for assisting with the lookup of a particular element such that the output of this function would take the place of %s in this expression |
59,120 | def make_python_identifier ( string , namespace = None , reserved_words = None , convert = 'drop' , handle = 'force' ) : if namespace is None : namespace = dict ( ) if reserved_words is None : reserved_words = list ( ) if string in namespace : return namespace [ string ] , namespace s = string . lower ( ) s = s . strip ( ) s = re . sub ( '[\\s\\t\\n]+' , '_' , s ) if convert == 'hex' : s = '' . join ( [ c . encode ( "hex" ) if re . findall ( '[^\p{l}\p{m}\p{n}_]' , c ) else c for c in s ] ) elif convert == 'drop' : s = re . sub ( '[^\p{l}\p{m}\p{n}_]' , '' , s ) s = re . sub ( '^[^\p{l}_]+' , '' , s ) while ( s in keyword . kwlist or s in namespace . values ( ) or s in reserved_words ) : if handle == 'throw' : raise NameError ( s + ' already exists in namespace or is a reserved word' ) if handle == 'force' : if re . match ( ".*?_\d+$" , s ) : i = re . match ( ".*?_(\d+)$" , s ) . groups ( ) [ 0 ] s = s . strip ( '_' + i ) + '_' + str ( int ( i ) + 1 ) else : s += '_1' namespace [ string ] = s return s , namespace | Takes an arbitrary string and creates a valid Python identifier . |
59,121 | def make_flat_df ( frames , return_addresses ) : visited = list ( map ( lambda x : visit_addresses ( x , return_addresses ) , frames ) ) return pd . DataFrame ( visited ) | Takes a list of dictionaries each representing what is returned from the model at a particular time and creates a dataframe whose columns correspond to the keys of return addresses |
59,122 | def visit_addresses ( frame , return_addresses ) : outdict = dict ( ) for real_name , ( pyname , address ) in return_addresses . items ( ) : if address : xrval = frame [ pyname ] . loc [ address ] if xrval . size > 1 : outdict [ real_name ] = xrval else : outdict [ real_name ] = float ( np . squeeze ( xrval . values ) ) else : outdict [ real_name ] = frame [ pyname ] return outdict | Visits all of the addresses returns a new dict which contains just the addressed elements |
59,123 | def validate_request ( request ) : if getattr ( settings , 'BASICAUTH_DISABLE' , False ) : return True if 'HTTP_AUTHORIZATION' not in request . META : return False authorization_header = request . META [ 'HTTP_AUTHORIZATION' ] ret = extract_basicauth ( authorization_header ) if not ret : return False username , password = ret raw_pass = settings . BASICAUTH_USERS . get ( username ) if raw_pass is None : return False if not constant_time_compare ( raw_pass , password ) : return False request . META [ 'REMOTE_USER' ] = username return True | Check an incoming request . |
59,124 | def _find_address_range ( addresses ) : first = last = addresses [ 0 ] last_index = 0 for ip in addresses [ 1 : ] : if ip . _ip == last . _ip + 1 : last = ip last_index += 1 else : break return ( first , last , last_index ) | Find a sequence of addresses . |
59,125 | def _prefix_from_prefix_int ( self , prefixlen ) : if not isinstance ( prefixlen , ( int , long ) ) : raise NetmaskValueError ( '%r is not an integer' % prefixlen ) prefixlen = int ( prefixlen ) if not ( 0 <= prefixlen <= self . _max_prefixlen ) : raise NetmaskValueError ( '%d is not a valid prefix length' % prefixlen ) return prefixlen | Validate and return a prefix length integer . |
59,126 | def output_colored ( code , text , is_bold = False ) : if is_bold : code = '1;%s' % code return '\033[%sm%s\033[0m' % ( code , text ) | Create function to output with color sequence |
59,127 | def _set_asset_paths ( self , app ) : webpack_stats = app . config [ 'WEBPACK_MANIFEST_PATH' ] try : with app . open_resource ( webpack_stats , 'r' ) as stats_json : stats = json . load ( stats_json ) if app . config [ 'WEBPACK_ASSETS_URL' ] : self . assets_url = app . config [ 'WEBPACK_ASSETS_URL' ] else : self . assets_url = stats [ 'publicPath' ] self . assets = stats [ 'assets' ] except IOError : raise RuntimeError ( "Flask-Webpack requires 'WEBPACK_MANIFEST_PATH' to be set and " "it must point to a valid json file." ) | Read in the manifest json file which acts as a manifest for assets . This allows us to get the asset path as well as hashed names . |
59,128 | def javascript_tag ( self , * args ) : tags = [ ] for arg in args : asset_path = self . asset_url_for ( '{0}.js' . format ( arg ) ) if asset_path : tags . append ( '<script src="{0}"></script>' . format ( asset_path ) ) return '\n' . join ( tags ) | Convenience tag to output 1 or more javascript tags . |
59,129 | def asset_url_for ( self , asset ) : if '//' in asset : return asset if asset not in self . assets : return None return '{0}{1}' . format ( self . assets_url , self . assets [ asset ] ) | Lookup the hashed asset path of a file name unless it starts with something that resembles a web address then take it as is . |
59,130 | def pre_change_receiver ( self , instance : Model , action : Action ) : if action == Action . CREATE : group_names = set ( ) else : group_names = set ( self . group_names ( instance ) ) if not hasattr ( instance , '__instance_groups' ) : instance . __instance_groups = threading . local ( ) instance . __instance_groups . observers = { } if not hasattr ( instance . __instance_groups , 'observers' ) : instance . __instance_groups . observers = { } instance . __instance_groups . observers [ self ] = group_names | Entry point for triggering the old_binding from save signals . |
59,131 | def post_change_receiver ( self , instance : Model , action : Action , ** kwargs ) : try : old_group_names = instance . __instance_groups . observers [ self ] except ( ValueError , KeyError ) : old_group_names = set ( ) if action == Action . DELETE : new_group_names = set ( ) else : new_group_names = set ( self . group_names ( instance ) ) self . send_messages ( instance , old_group_names - new_group_names , Action . DELETE , ** kwargs ) self . send_messages ( instance , old_group_names & new_group_names , Action . UPDATE , ** kwargs ) self . send_messages ( instance , new_group_names - old_group_names , Action . CREATE , ** kwargs ) | Triggers the old_binding to possibly send to its group . |
59,132 | def get_queryset ( self , ** kwargs ) -> QuerySet : assert self . queryset is not None , ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self . __class__ . __name__ ) queryset = self . queryset if isinstance ( queryset , QuerySet ) : queryset = queryset . all ( ) return queryset | Get the list of items for this view . This must be an iterable and may be a queryset . Defaults to using self . queryset . |
59,133 | def get_serializer_class ( self , ** kwargs ) -> Type [ Serializer ] : assert self . serializer_class is not None , ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self . __class__ . __name__ ) return self . serializer_class | Return the class to use for the serializer . Defaults to using self . serializer_class . |
59,134 | def view_as_consumer ( wrapped_view : typing . Callable [ [ HttpRequest ] , HttpResponse ] , mapped_actions : typing . Optional [ typing . Dict [ str , str ] ] = None ) -> Type [ AsyncConsumer ] : if mapped_actions is None : mapped_actions = { 'create' : 'PUT' , 'update' : 'PATCH' , 'list' : 'GET' , 'retrieve' : 'GET' } class DjangoViewWrapper ( DjangoViewAsConsumer ) : view = wrapped_view actions = mapped_actions return DjangoViewWrapper | Wrap a django View so that it will be triggered by actions over this json websocket consumer . |
59,135 | async def check_permissions ( self , action : str , ** kwargs ) : for permission in await self . get_permissions ( action = action , ** kwargs ) : if not await ensure_async ( permission . has_permission ) ( scope = self . scope , consumer = self , action = action , ** kwargs ) : raise PermissionDenied ( ) | Check if the action should be permitted . Raises an appropriate exception if the request is not permitted . |
59,136 | async def handle_exception ( self , exc : Exception , action : str , request_id ) : if isinstance ( exc , APIException ) : await self . reply ( action = action , errors = self . _format_errors ( exc . detail ) , status = exc . status_code , request_id = request_id ) elif exc == Http404 or isinstance ( exc , Http404 ) : await self . reply ( action = action , errors = self . _format_errors ( 'Not found' ) , status = 404 , request_id = request_id ) else : raise exc | Handle any exception that occurs by sending an appropriate message |
59,137 | async def receive_json ( self , content : typing . Dict , ** kwargs ) : request_id = content . pop ( 'request_id' ) action = content . pop ( 'action' ) await self . handle_action ( action , request_id = request_id , ** content ) | Called with decoded JSON content . |
59,138 | def action ( atomic = None , ** kwargs ) : def decorator ( func ) : if atomic is None : _atomic = getattr ( settings , 'ATOMIC_REQUESTS' , False ) else : _atomic = atomic func . action = True func . kwargs = kwargs if asyncio . iscoroutinefunction ( func ) : if _atomic : raise ValueError ( 'Only synchronous actions can be atomic' ) return func if _atomic : func = transaction . atomic ( func ) @ wraps ( func ) async def async_f ( self : AsyncAPIConsumer , * args , ** _kwargs ) : result , status = await database_sync_to_async ( func ) ( self , * args , ** _kwargs ) return result , status async_f . action = True async_f . kwargs = kwargs async_f . __name__ = func . __name__ return async_f return decorator | Mark a method as an action . |
59,139 | def datetime_parser ( s ) : try : ts = arrow . get ( s ) if ts . tzinfo == arrow . get ( ) . tzinfo : ts = ts . replace ( tzinfo = 'local' ) except : c = pdt . Calendar ( ) result , what = c . parse ( s ) ts = None if what in ( 1 , 2 , 3 ) : ts = datetime . datetime ( * result [ : 6 ] ) ts = arrow . get ( ts ) ts = ts . replace ( tzinfo = 'local' ) return ts if ts is None : raise ValueError ( "Cannot parse timestamp '" + s + "'" ) return ts | Parse timestamp s in local time . First the arrow parser is used if it fails the parsedatetime parser is used . |
59,140 | def seek ( self , offset : int = 0 , * args , ** kwargs ) : return self . fp . seek ( offset , * args , ** kwargs ) | A shortcut to self . fp . seek . |
59,141 | def set_title ( self , title : str , url : str = None ) -> None : self . title = title self . url = url | Sets the title of the embed . |
59,142 | def set_timestamp ( self , time : Union [ str , datetime . datetime ] = None , now : bool = False ) -> None : if now : self . timestamp = str ( datetime . datetime . utcnow ( ) ) else : self . timestamp = str ( time ) | Sets the timestamp of the embed . |
59,143 | def add_field ( self , name : str , value : str , inline : bool = True ) -> None : field = { 'name' : name , 'value' : value , 'inline' : inline } self . fields . append ( field ) | Adds an embed field . |
59,144 | def set_author ( self , name : str , icon_url : str = None , url : str = None ) -> None : self . author = { 'name' : name , 'icon_url' : icon_url , 'url' : url } | Sets the author of the embed . |
59,145 | def set_footer ( self , text : str , icon_url : str = None ) -> None : self . footer = { 'text' : text , 'icon_url' : icon_url } | Sets the footer of the embed . |
59,146 | async def init ( app , loop ) : app . session = aiohttp . ClientSession ( loop = loop ) app . webhook = Webhook . Async ( webhook_url , session = app . session ) em = Embed ( color = 0x2ecc71 ) em . set_author ( '[INFO] Starting Worker' ) em . description = 'Host: {}' . format ( socket . gethostname ( ) ) await app . webhook . send ( embed = em ) | Sends a message to the webhook channel when server starts . |
59,147 | async def server_stop ( app , loop ) : em = Embed ( color = 0xe67e22 ) em . set_footer ( 'Host: {}' . format ( socket . gethostname ( ) ) ) em . description = '[INFO] Server Stopped' await app . webhook . send ( embed = em ) await app . session . close ( ) | Sends a message to the webhook channel when server stops . |
59,148 | def get_deprecated_msg ( self , wrapped , instance ) : if instance is None : if inspect . isclass ( wrapped ) : fmt = "Call to deprecated class {name}." else : fmt = "Call to deprecated function (or staticmethod) {name}." else : if inspect . isclass ( instance ) : fmt = "Call to deprecated class method {name}." else : fmt = "Call to deprecated method {name}." if self . reason : fmt += " ({reason})" if self . version : fmt += " -- Deprecated since version {version}." return fmt . format ( name = wrapped . __name__ , reason = self . reason or "" , version = self . version or "" ) | Get the deprecation warning message for the user . |
59,149 | def slack_user ( request , api_data ) : if request . user . is_anonymous : return request , api_data data = deepcopy ( api_data ) slacker , _ = SlackUser . objects . get_or_create ( slacker = request . user ) slacker . access_token = data . pop ( 'access_token' ) slacker . extras = data slacker . save ( ) messages . add_message ( request , messages . SUCCESS , 'Your account has been successfully updated with ' 'Slack. You can share your messages within your slack ' 'domain.' ) return request , api_data | Pipeline for backward compatibility prior to 1 . 0 . 0 version . In case if you re willing maintain slack_user table . |
59,150 | def read ( varin , fname = 'MS2_L10.mat.txt' ) : d = np . loadtxt ( fname , comments = '*' ) if fname == 'MS2_L10.mat.txt' : var = [ 'lat' , 'lon' , 'depth' , 'temp' , 'density' , 'sigma' , 'oxygen' , 'voltage 2' , 'voltage 3' , 'fluorescence-CDOM' , 'fluorescence-ECO' , 'turbidity' , 'pressure' , 'salinity' , 'RINKO temperature' , 'RINKO DO - CTD temp' , 'RINKO DO - RINKO temp' , 'bottom' , 'PAR' ] elif ( fname == 'MS09_L05.mat.txt' ) or ( fname == 'MS09_L10.mat.txt' ) or ( fname == 'MS08_L12.mat.txt' ) : var = [ 'lat' , 'lon' , 'depth' , 'temp' , 'density' , 'sigma' , 'oxygen' , 'voltage 2' , 'voltage 3' , 'voltage 4' , 'fluorescence-CDOM' , 'fluorescence-ECO' , 'turbidity' , 'pressure' , 'salinity' , 'RINKO temperature' , 'RINKO DO - CTD temp' , 'RINKO DO - RINKO temp' , 'bottom' , 'PAR' ] return d [ : , 0 ] , d [ : , 1 ] , d [ : , 2 ] , d [ : , var . index ( varin ) ] | Read in dataset for variable var |
59,151 | def show ( cmap , var , vmin = None , vmax = None ) : lat , lon , z , data = read ( var ) fig = plt . figure ( figsize = ( 16 , 12 ) ) ax = fig . add_subplot ( 3 , 1 , 1 ) map1 = ax . scatter ( lon , - z , c = data , cmap = 'gray' , s = 10 , linewidths = 0. , vmin = vmin , vmax = vmax ) plt . colorbar ( map1 , ax = ax ) ax = fig . add_subplot ( 3 , 1 , 2 ) map1 = ax . scatter ( lon , - z , c = data , cmap = 'jet' , s = 10 , linewidths = 0. , vmin = vmin , vmax = vmax ) plt . colorbar ( map1 , ax = ax ) ax = fig . add_subplot ( 3 , 1 , 3 ) map1 = ax . scatter ( lon , - z , c = data , cmap = cmap , s = 10 , linewidths = 0. , vmin = vmin , vmax = vmax ) ax . set_xlabel ( 'Longitude [degrees]' ) ax . set_ylabel ( 'Depth [m]' ) plt . colorbar ( map1 , ax = ax ) plt . suptitle ( var ) | Show a colormap for a chosen input variable var side by side with black and white and jet colormaps . |
59,152 | def plot_data ( ) : var = [ 'temp' , 'oxygen' , 'salinity' , 'fluorescence-ECO' , 'density' , 'PAR' , 'turbidity' , 'fluorescence-CDOM' ] lims = np . array ( [ [ 26 , 33 ] , [ 0 , 10 ] , [ 0 , 36 ] , [ 0 , 6 ] , [ 1005 , 1025 ] , [ 0 , 0.6 ] , [ 0 , 2 ] , [ 0 , 9 ] ] ) for fname in fnames : fig , axes = plt . subplots ( nrows = 4 , ncols = 2 ) fig . set_size_inches ( 20 , 10 ) fig . subplots_adjust ( top = 0.95 , bottom = 0.01 , left = 0.2 , right = 0.99 , wspace = 0.0 , hspace = 0.07 ) i = 0 for ax , Var , cmap in zip ( axes . flat , var , cmaps ) : lat , lon , z , data = test . read ( Var , fname ) map1 = ax . scatter ( lat , - z , c = data , cmap = cmap , s = 10 , linewidths = 0. , vmin = lims [ i , 0 ] , vmax = lims [ i , 1 ] ) y_formatter = mpl . ticker . ScalarFormatter ( useOffset = False ) ax . xaxis . set_major_formatter ( y_formatter ) if i == 6 : ax . set_xlabel ( 'Latitude [degrees]' ) ax . set_ylabel ( 'Depth [m]' ) else : ax . set_xticklabels ( [ ] ) ax . set_yticklabels ( [ ] ) ax . set_ylim ( - z . max ( ) , 0 ) ax . set_xlim ( lat . min ( ) , lat . max ( ) ) cb = plt . colorbar ( map1 , ax = ax , pad = 0.02 ) cb . set_label ( cmap . name + ' [' + '$' + cmap . units + '$]' ) i += 1 fig . savefig ( 'figures/' + fname . split ( '.' ) [ 0 ] + '.png' , bbox_inches = 'tight' ) | Plot sample data up with the fancy colormaps . |
59,153 | def plot_lightness ( saveplot = False ) : from colorspacious import cspace_converter dc = 1. x = np . linspace ( 0.0 , 1.0 , 256 ) locs = [ ] fig = plt . figure ( figsize = ( 16 , 5 ) ) ax = fig . add_subplot ( 111 ) fig . subplots_adjust ( left = 0.03 , right = 0.97 ) ax . set_xlim ( - 0.1 , len ( cm . cmap_d ) / 2. + 0.1 ) ax . set_ylim ( 0 , 100 ) ax . set_xlabel ( 'Lightness for each colormap' , fontsize = 14 ) for j , cmapname in enumerate ( cm . cmapnames ) : if '_r' in cmapname : continue cmap = cm . cmap_d [ cmapname ] rgb = cmap ( x ) [ np . newaxis , : , : 3 ] lab = cspace_converter ( "sRGB1" , "CAM02-UCS" ) ( rgb ) L = lab [ 0 , : , 0 ] if L [ - 1 ] > L [ 0 ] : ax . scatter ( x + j * dc , L , c = x , cmap = cmap , s = 200 , linewidths = 0. ) else : ax . scatter ( x + j * dc , L [ : : - 1 ] , c = x [ : : - 1 ] , cmap = cmap , s = 200 , linewidths = 0. ) locs . append ( x [ - 1 ] + j * dc ) ax . xaxis . set_ticks_position ( 'top' ) ticker = mpl . ticker . FixedLocator ( locs ) ax . xaxis . set_major_locator ( ticker ) formatter = mpl . ticker . FixedFormatter ( [ cmapname for cmapname in cm . cmapnames ] ) ax . xaxis . set_major_formatter ( formatter ) labels = ax . get_xticklabels ( ) for label in labels : label . set_rotation ( 60 ) if saveplot : fig . savefig ( 'figures/lightness.png' , bbox_inches = 'tight' ) fig . savefig ( 'figures/lightness.pdf' , bbox_inches = 'tight' ) plt . show ( ) | Plot lightness of colormaps together . |
59,154 | def plot_gallery ( saveplot = False ) : from colorspacious import cspace_converter gradient = np . linspace ( 0 , 1 , 256 ) gradient = np . vstack ( ( gradient , gradient ) ) x = np . linspace ( 0.0 , 1.0 , 256 ) fig , axes = plt . subplots ( nrows = int ( len ( cm . cmap_d ) / 2 ) , ncols = 1 , figsize = ( 6 , 12 ) ) fig . subplots_adjust ( top = 0.99 , bottom = 0.01 , left = 0.2 , right = 0.99 , wspace = 0.05 ) for ax , cmapname in zip ( axes , cm . cmapnames ) : if '_r' in cmapname : continue cmap = cm . cmap_d [ cmapname ] rgb = cmap ( x ) [ np . newaxis , : , : 3 ] jch = cspace_converter ( "sRGB1" , "CAM02-UCS" ) ( rgb ) L = jch [ 0 , : , 0 ] L = np . float32 ( np . vstack ( ( L , L , L ) ) ) ax . imshow ( gradient , aspect = 'auto' , cmap = cmap ) pos1 = ax . get_position ( ) pos2 = [ pos1 . x0 , pos1 . y0 , pos1 . width , pos1 . height / 3.0 ] axbw = fig . add_axes ( pos2 ) axbw . set_axis_off ( ) axbw . imshow ( L , aspect = 'auto' , cmap = cm . gray , vmin = 0 , vmax = 100. ) pos = list ( ax . get_position ( ) . bounds ) x_text = pos [ 0 ] - 0.01 y_text = pos [ 1 ] + pos [ 3 ] / 2. fig . text ( x_text , y_text , cmap . name , va = 'center' , ha = 'right' ) for ax in axes : ax . set_axis_off ( ) if saveplot : fig . savefig ( 'figures/gallery.pdf' , bbox_inches = 'tight' ) fig . savefig ( 'figures/gallery.png' , bbox_inches = 'tight' ) plt . show ( ) | Make plot of colormaps and labels like in the matplotlib gallery . |
59,155 | def wrap_viscm ( cmap , dpi = 100 , saveplot = False ) : from viscm import viscm viscm ( cmap ) fig = plt . gcf ( ) fig . set_size_inches ( 22 , 10 ) plt . show ( ) if saveplot : fig . savefig ( 'figures/eval_' + cmap . name + '.png' , bbox_inches = 'tight' , dpi = dpi ) fig . savefig ( 'figures/eval_' + cmap . name + '.pdf' , bbox_inches = 'tight' , dpi = dpi ) | Evaluate goodness of colormap using perceptual deltas . |
59,156 | def quick_plot ( cmap , fname = None , fig = None , ax = None , N = 10 ) : x = np . linspace ( 0 , 10 , N ) X , _ = np . meshgrid ( x , x ) if ax is None : fig = plt . figure ( ) ax = fig . add_subplot ( 111 ) mappable = ax . pcolor ( X , cmap = cmap ) ax . set_title ( cmap . name , fontsize = 14 ) ax . set_xticks ( [ ] ) ax . set_yticks ( [ ] ) plt . colorbar ( mappable ) plt . show ( ) if fname is not None : plt . savefig ( fname + '.png' , bbox_inches = 'tight' ) | Show quick test of a colormap . |
59,157 | def print_colormaps ( cmaps , N = 256 , returnrgb = True , savefiles = False ) : rgb = [ ] for cmap in cmaps : rgbtemp = cmap ( np . linspace ( 0 , 1 , N ) ) [ np . newaxis , : , : 3 ] [ 0 ] if savefiles : np . savetxt ( cmap . name + '-rgb.txt' , rgbtemp ) rgb . append ( rgbtemp ) if returnrgb : return rgb | Print colormaps in 256 RGB colors to text files . |
59,158 | def cmap ( rgbin , N = 256 ) : if not isinstance ( rgbin [ 0 ] , _string_types ) : if rgbin . max ( ) > 1 : rgbin = rgbin / 256. cmap = mpl . colors . LinearSegmentedColormap . from_list ( 'mycmap' , rgbin , N = N ) return cmap | Input an array of rgb values to generate a colormap . |
59,159 | def lighten ( cmapin , alpha ) : return cmap ( cmapin ( np . linspace ( 0 , 1 , cmapin . N ) , alpha ) ) | Lighten a colormap by adding alpha < 1 . |
59,160 | def crop_by_percent ( cmap , per , which = 'both' , N = None ) : if which == 'both' : vmin = - 100 vmax = 100 pivot = 0 dmax = per elif which == 'min' : vmax = 10 pivot = 5 vmin = ( 0 + per / 100 ) * 2 * pivot dmax = None elif which == 'max' : vmin = 0 pivot = 5 vmax = ( 1 - per / 100 ) * 2 * pivot dmax = None newcmap = crop ( cmap , vmin , vmax , pivot , dmax = dmax , N = N ) return newcmap | Crop end or ends of a colormap by per percent . |
59,161 | def _premium ( fn ) : @ _functools . wraps ( fn ) def _fn ( self , * args , ** kwargs ) : if self . _lite : raise RuntimeError ( 'Premium API not available in lite access.' ) return fn ( self , * args , ** kwargs ) return _fn | Premium decorator for APIs that require premium access level . |
59,162 | def make_retrieveParameters ( offset = 1 , count = 100 , name = 'RS' , sort = 'D' ) : return _OrderedDict ( [ ( 'firstRecord' , offset ) , ( 'count' , count ) , ( 'sortField' , _OrderedDict ( [ ( 'name' , name ) , ( 'sort' , sort ) ] ) ) ] ) | Create retrieve parameters dictionary to be used with APIs . |
59,163 | def connect ( self ) : if not self . _SID : self . _SID = self . _auth . service . authenticate ( ) print ( 'Authenticated (SID: %s)' % self . _SID ) self . _search . set_options ( headers = { 'Cookie' : 'SID="%s"' % self . _SID } ) self . _auth . options . headers . update ( { 'Cookie' : 'SID="%s"' % self . _SID } ) return self . _SID | Authenticate to WOS and set the SID cookie . |
59,164 | def close ( self ) : if self . _SID : self . _auth . service . closeSession ( ) self . _SID = None | The close operation loads the session if it is valid and then closes it and releases the session seat . All the session data are deleted and become invalid after the request is processed . The session ID can no longer be used in subsequent requests . |
59,165 | def search ( self , query , count = 5 , offset = 1 , editions = None , symbolicTimeSpan = None , timeSpan = None , retrieveParameters = None ) : return self . _search . service . search ( queryParameters = _OrderedDict ( [ ( 'databaseId' , 'WOS' ) , ( 'userQuery' , query ) , ( 'editions' , editions ) , ( 'symbolicTimeSpan' , symbolicTimeSpan ) , ( 'timeSpan' , timeSpan ) , ( 'queryLanguage' , 'en' ) ] ) , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) ) | The search operation submits a search query to the specified database edition and retrieves data . This operation returns a query ID that can be used in subsequent operations to retrieve more records . |
59,166 | def citedReferences ( self , uid , count = 100 , offset = 1 , retrieveParameters = None ) : return self . _search . service . citedReferences ( databaseId = 'WOS' , uid = uid , queryLanguage = 'en' , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) ) | The citedReferences operation returns references cited by an article identified by a unique identifier . You may specify only one identifier per request . |
59,167 | def citedReferencesRetrieve ( self , queryId , count = 100 , offset = 1 , retrieveParameters = None ) : return self . _search . service . citedReferencesRetrieve ( queryId = queryId , retrieveParameters = ( retrieveParameters or self . make_retrieveParameters ( offset , count ) ) ) | The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation . |
59,168 | def single ( wosclient , wos_query , xml_query = None , count = 5 , offset = 1 ) : result = wosclient . search ( wos_query , count , offset ) xml = _re . sub ( ' xmlns="[^"]+"' , '' , result . records , count = 1 ) . encode ( 'utf-8' ) if xml_query : xml = _ET . fromstring ( xml ) return [ el . text for el in xml . findall ( xml_query ) ] else : return _minidom . parseString ( xml ) . toprettyxml ( ) | Perform a single Web of Science query and then XML query the results . |
59,169 | def query ( wosclient , wos_query , xml_query = None , count = 5 , offset = 1 , limit = 100 ) : results = [ single ( wosclient , wos_query , xml_query , min ( limit , count - x + 1 ) , x ) for x in range ( offset , count + 1 , limit ) ] if xml_query : return [ el for res in results for el in res ] else : pattern = _re . compile ( r'^<\?xml.*?\n<records>\n|\n</records>$.*' ) return ( '<?xml version="1.0" ?>\n<records>' + '\n' . join ( pattern . sub ( '' , res ) for res in results ) + '</records>' ) | Query Web of Science and XML query results with multiple requests . |
59,170 | def doi_to_wos ( wosclient , doi ) : results = query ( wosclient , 'DO="%s"' % doi , './REC/UID' , count = 1 ) return results [ 0 ] . lstrip ( 'WOS:' ) if results else None | Convert DOI to WOS identifier . |
59,171 | def sql_fingerprint ( query , hide_columns = True ) : parsed_query = parse ( query ) [ 0 ] sql_recursively_simplify ( parsed_query , hide_columns = hide_columns ) return str ( parsed_query ) | Simplify a query taking away exact values and fields selected . |
59,172 | def match_keyword ( token , keywords ) : if not token : return False if not token . is_keyword : return False return token . value . upper ( ) in keywords | Checks if the given token represents one of the given keywords |
59,173 | def _is_group ( token ) : is_group = token . is_group if isinstance ( is_group , bool ) : return is_group else : return is_group ( ) | sqlparse 0 . 2 . 2 changed it from a callable to a bool property |
59,174 | def sorted_names ( names ) : names = list ( names ) have_default = False if 'default' in names : names . remove ( 'default' ) have_default = True sorted_names = sorted ( names ) if have_default : sorted_names = [ 'default' ] + sorted_names return sorted_names | Sort a list of names but keep the word default first if it s there . |
59,175 | def record_diff ( old , new ) : return '\n' . join ( difflib . ndiff ( [ '%s: %s' % ( k , v ) for op in old for k , v in op . items ( ) ] , [ '%s: %s' % ( k , v ) for op in new for k , v in op . items ( ) ] , ) ) | Generate a human - readable diff of two performance records . |
59,176 | def dequeue ( self , block = True ) : return self . queue . get ( block , self . queue_get_timeout ) | Dequeue a record and return item . |
59,177 | def start ( self ) : self . _thread = t = threading . Thread ( target = self . _monitor ) t . setDaemon ( True ) t . start ( ) | Start the listener . |
59,178 | def handle ( self , record ) : record = self . prepare ( record ) for handler in self . handlers : handler ( record ) | Handle an item . |
59,179 | def _monitor ( self ) : err_msg = ( "invalid internal state:" " _stop_nowait can not be set if _stop is not set" ) assert self . _stop . isSet ( ) or not self . _stop_nowait . isSet ( ) , err_msg q = self . queue has_task_done = hasattr ( q , 'task_done' ) while not self . _stop . isSet ( ) : try : record = self . dequeue ( True ) if record is self . _sentinel_item : break self . handle ( record ) if has_task_done : q . task_done ( ) except queue . Empty : pass while not self . _stop_nowait . isSet ( ) : try : record = self . dequeue ( False ) if record is self . _sentinel_item : break self . handle ( record ) if has_task_done : q . task_done ( ) except queue . Empty : break | Monitor the queue for items and ask the handler to deal with them . |
59,180 | def stop ( self , nowait = False ) : self . _stop . set ( ) if nowait : self . _stop_nowait . set ( ) self . queue . put_nowait ( self . _sentinel_item ) if ( self . _thread . isAlive ( ) and self . _thread is not threading . currentThread ( ) ) : self . _thread . join ( ) self . _thread = None | Stop the listener . |
59,181 | def terminate ( self , nowait = False ) : logger . debug ( "Acquiring lock for service termination" ) with self . lock : logger . debug ( "Terminating service" ) if not self . listener : logger . warning ( "Service already stopped." ) return self . listener . stop ( nowait ) try : if not nowait : self . _post_log_batch ( ) except Exception : if self . error_handler : self . error_handler ( sys . exc_info ( ) ) else : raise finally : self . queue = None self . listener = None | Finalize and stop service |
59,182 | def process_log ( self , ** log_item ) : logger . debug ( "Processing log item: %s" , log_item ) self . log_batch . append ( log_item ) if len ( self . log_batch ) >= self . log_batch_size : self . _post_log_batch ( ) | Special handler for log messages . |
59,183 | def process_item ( self , item ) : logger . debug ( "Processing item: %s (queue size: %s)" , item , self . queue . qsize ( ) ) method , kwargs = item if method not in self . supported_methods : raise Error ( "Not expected service method: {}" . format ( method ) ) try : if method == "log" : self . process_log ( ** kwargs ) else : self . _post_log_batch ( ) getattr ( self . rp_client , method ) ( ** kwargs ) except Exception : if self . error_handler : self . error_handler ( sys . exc_info ( ) ) else : self . terminate ( nowait = True ) raise | Main item handler . |
59,184 | def log ( self , time , message , level = None , attachment = None ) : logger . debug ( "log queued" ) args = { "time" : time , "message" : message , "level" : level , "attachment" : attachment , } self . queue . put_nowait ( ( "log" , args ) ) | Logs a message with attachment . |
59,185 | def log_batch ( self , log_data ) : url = uri_join ( self . base_url , "log" ) attachments = [ ] for log_item in log_data : log_item [ "item_id" ] = self . stack [ - 1 ] attachment = log_item . get ( "attachment" , None ) if "attachment" in log_item : del log_item [ "attachment" ] if attachment : if not isinstance ( attachment , collections . Mapping ) : attachment = { "data" : attachment } name = attachment . get ( "name" , str ( uuid . uuid4 ( ) ) ) log_item [ "file" ] = { "name" : name } attachments . append ( ( "file" , ( name , attachment [ "data" ] , attachment . get ( "mime" , "application/octet-stream" ) ) ) ) files = [ ( "json_request_part" , ( None , json . dumps ( log_data ) , "application/json" ) ) ] files . extend ( attachments ) from reportportal_client import POST_LOGBATCH_RETRY_COUNT for i in range ( POST_LOGBATCH_RETRY_COUNT ) : try : r = self . session . post ( url = url , files = files , verify = self . verify_ssl ) except KeyError : if i < POST_LOGBATCH_RETRY_COUNT - 1 : continue else : raise break logger . debug ( "log_batch - Stack: %s" , self . stack ) logger . debug ( "log_batch response: %s" , r . text ) return _get_data ( r ) | Logs batch of messages with attachment . |
59,186 | def git_versions_from_keywords ( keywords , tag_prefix , verbose ) : if not keywords : raise NotThisMethod ( "no keywords at all, weird" ) date = keywords . get ( "date" ) if date is not None : date = date . strip ( ) . replace ( " " , "T" , 1 ) . replace ( " " , "" , 1 ) refnames = keywords [ "refnames" ] . strip ( ) if refnames . startswith ( "$Format" ) : if verbose : print ( "keywords are unexpanded, not using" ) raise NotThisMethod ( "unexpanded keywords, not a git-archive tarball" ) refs = set ( [ r . strip ( ) for r in refnames . strip ( "()" ) . split ( "," ) ] ) TAG = "tag: " tags = set ( [ r [ len ( TAG ) : ] for r in refs if r . startswith ( TAG ) ] ) if not tags : tags = set ( [ r for r in refs if re . search ( r'\d' , r ) ] ) if verbose : print ( "discarding '%s', no digits" % "," . join ( refs - tags ) ) if verbose : print ( "likely tags: %s" % "," . join ( sorted ( tags ) ) ) for ref in sorted ( tags ) : if ref . startswith ( tag_prefix ) : r = ref [ len ( tag_prefix ) : ] if verbose : print ( "picking %s" % r ) return { "version" : r , "full-revisionid" : keywords [ "full" ] . strip ( ) , "dirty" : False , "error" : None , "date" : date , "branch" : None } if verbose : print ( "no suitable tags, using unknown + full revision id" ) return { "version" : "0+unknown" , "full-revisionid" : keywords [ "full" ] . strip ( ) , "dirty" : False , "error" : "no suitable tags" , "date" : None , "branch" : None } | Get version information from git keywords . |
59,187 | def render_pep440_branch_based ( pieces ) : replacements = ( [ ' ' , '.' ] , [ '(' , '' ] , [ ')' , '' ] , [ '\\' , '.' ] , [ '/' , '.' ] ) branch_name = pieces . get ( 'branch' ) or '' if branch_name : for old , new in replacements : branch_name = branch_name . replace ( old , new ) else : branch_name = 'unknown_branch' if pieces [ "closest-tag" ] : rendered = pieces [ "closest-tag" ] if pieces [ "distance" ] or pieces [ "dirty" ] : rendered += '.dev0' + plus_or_dot ( pieces ) rendered += "%d.%s.g%s" % ( pieces [ "distance" ] , branch_name , pieces [ 'short' ] ) if pieces [ "dirty" ] : rendered += ".dirty" else : rendered = "0+untagged.%d.%s.g%s" % ( pieces [ "distance" ] , branch_name , pieces [ 'short' ] ) if pieces [ "dirty" ] : rendered += ".dirty" return rendered | Build up version string with post - release local version identifier . |
59,188 | def render ( pieces , style ) : if pieces [ "error" ] : return { "version" : "unknown" , "full-revisionid" : pieces . get ( "long" ) , "dirty" : None , "error" : pieces [ "error" ] , "date" : None } if not style or style == "default" : style = "pep440" if style == "pep440" : rendered = render_pep440 ( pieces ) elif style == "pep440-pre" : rendered = render_pep440_pre ( pieces ) elif style == "pep440-post" : rendered = render_pep440_post ( pieces ) elif style == "pep440-old" : rendered = render_pep440_old ( pieces ) elif style == "pep440-branch-based" : rendered = render_pep440_branch_based ( pieces ) elif style == "git-describe" : rendered = render_git_describe ( pieces ) elif style == "git-describe-long" : rendered = render_git_describe_long ( pieces ) else : raise ValueError ( "unknown style '%s'" % style ) return { "version" : rendered , "full-revisionid" : pieces [ "long" ] , "dirty" : pieces [ "dirty" ] , "error" : None , "date" : pieces . get ( "date" ) } | Render the given version pieces into the requested style . |
59,189 | def do_setup ( ) : root = get_root ( ) try : cfg = get_config_from_root ( root ) except ( EnvironmentError , configparser . NoSectionError , configparser . NoOptionError ) as e : if isinstance ( e , ( EnvironmentError , configparser . NoSectionError ) ) : print ( "Adding sample versioneer config to setup.cfg" , file = sys . stderr ) with open ( os . path . join ( root , "setup.cfg" ) , "a" ) as f : f . write ( SAMPLE_CONFIG ) print ( CONFIG_ERROR , file = sys . stderr ) return 1 print ( " creating %s" % cfg . versionfile_source ) with open ( cfg . versionfile_source , "w" ) as f : LONG = LONG_VERSION_PY [ cfg . VCS ] f . write ( LONG % { "DOLLAR" : "$" , "STYLE" : cfg . style , "TAG_PREFIX" : cfg . tag_prefix , "PARENTDIR_PREFIX" : cfg . parentdir_prefix , "VERSIONFILE_SOURCE" : cfg . versionfile_source , } ) ipy = os . path . join ( os . path . dirname ( cfg . versionfile_source ) , "__init__.py" ) if os . path . exists ( ipy ) : try : with open ( ipy , "r" ) as f : old = f . read ( ) except EnvironmentError : old = "" if INIT_PY_SNIPPET_RE . search ( old ) is None : print ( " appending to %s" % ipy ) with open ( ipy , "a" ) as f : f . write ( INIT_PY_SNIPPET ) else : print ( " %s unmodified" % ipy ) else : print ( " %s doesn't exist, ok" % ipy ) ipy = None manifest_in = os . path . join ( root , "MANIFEST.in" ) simple_includes = set ( ) try : with open ( manifest_in , "r" ) as f : for line in f : if line . startswith ( "include " ) : for include in line . split ( ) [ 1 : ] : simple_includes . add ( include ) except EnvironmentError : pass if "versioneer.py" not in simple_includes : print ( " appending 'versioneer.py' to MANIFEST.in" ) with open ( manifest_in , "a" ) as f : f . write ( "include versioneer.py\n" ) else : print ( " 'versioneer.py' already in MANIFEST.in" ) if cfg . versionfile_source not in simple_includes : print ( " appending versionfile_source ('%s') to MANIFEST.in" % cfg . versionfile_source ) with open ( manifest_in , "a" ) as f : f . write ( "include %s\n" % cfg . versionfile_source ) else : print ( " versionfile_source already in MANIFEST.in" ) do_vcs_install ( manifest_in , cfg . versionfile_source , ipy ) return 0 | Do main VCS - independent setup function for installing Versioneer . |
59,190 | def scan_setup_py ( ) : found = set ( ) setters = False errors = 0 with open ( "setup.py" , "r" ) as f : for line in f . readlines ( ) : if "import versioneer" in line : found . add ( "import" ) if "versioneer.get_cmdclass(" in line : found . add ( "cmdclass" ) if "versioneer.get_version()" in line : found . add ( "get_version" ) if "versioneer.VCS" in line : setters = True if "versioneer.versionfile_source" in line : setters = True if len ( found ) != 3 : print ( "" ) print ( "Your setup.py appears to be missing some important items" ) print ( "(but I might be wrong). Please make sure it has something" ) print ( "roughly like the following:" ) print ( "" ) print ( " import versioneer" ) print ( " setup( version=versioneer.get_version()," ) print ( " cmdclass=versioneer.get_cmdclass(), ...)" ) print ( "" ) errors += 1 if setters : print ( "You should remove lines like 'versioneer.VCS = ' and" ) print ( "'versioneer.versionfile_source = ' . This configuration" ) print ( "now lives in setup.cfg, and should be removed from setup.py" ) print ( "" ) errors += 1 return errors | Validate the contents of setup . py against Versioneer s expectations . |
59,191 | def read ( fname ) : file_path = os . path . join ( SETUP_DIRNAME , fname ) with codecs . open ( file_path , encoding = 'utf-8' ) as rfh : return rfh . read ( ) | Read a file from the directory where setup . py resides |
59,192 | def func ( self , w , * args ) : x0 = args [ 0 ] x1 = args [ 1 ] n0 = x0 . shape [ 0 ] n1 = x1 . shape [ 0 ] n = max ( n0 , n1 ) * 10 idx0 = np . random . choice ( range ( n0 ) , size = n ) idx1 = np . random . choice ( range ( n1 ) , size = n ) b0 = np . ones ( ( n0 , 1 ) ) b1 = np . ones ( ( n1 , 1 ) ) i1 = self . i + 1 h = self . h h1 = h + 1 if sparse . issparse ( x0 ) : p0 = np . hstack ( ( sigm ( sparse . hstack ( ( x0 , b0 ) ) . dot ( w [ : - h1 ] . reshape ( i1 , h ) ) ) , b0 ) ) . dot ( w [ - h1 : ] . reshape ( h1 , 1 ) ) p1 = np . hstack ( ( sigm ( sparse . hstack ( ( x1 , b1 ) ) . dot ( w [ : - h1 ] . reshape ( i1 , h ) ) ) , b1 ) ) . dot ( w [ - h1 : ] . reshape ( h1 , 1 ) ) else : p0 = np . hstack ( ( sigm ( np . hstack ( ( x0 , b0 ) ) . dot ( w [ : - h1 ] . reshape ( i1 , h ) ) ) , b0 ) ) . dot ( w [ - h1 : ] . reshape ( h1 , 1 ) ) p1 = np . hstack ( ( sigm ( np . hstack ( ( x1 , b1 ) ) . dot ( w [ : - h1 ] . reshape ( i1 , h ) ) ) , b1 ) ) . dot ( w [ - h1 : ] . reshape ( h1 , 1 ) ) p0 = p0 [ idx0 ] p1 = p1 [ idx1 ] return .5 * ( sum ( ( 1 - p1 + p0 ) ** 2 ) / n + self . l1 * sum ( w [ : - h1 ] ** 2 ) / ( i1 * h ) + self . l2 * sum ( w [ - h1 : ] ** 2 ) / h1 ) | Return the costs of the neural network for predictions . |
59,193 | def fprime ( self , w , * args ) : x0 = args [ 0 ] x1 = args [ 1 ] n0 = x0 . shape [ 0 ] n1 = x1 . shape [ 0 ] n = max ( n0 , n1 ) * 10 idx0 = np . random . choice ( range ( n0 ) , size = n ) idx1 = np . random . choice ( range ( n1 ) , size = n ) b = np . ones ( ( n , 1 ) ) i1 = self . i + 1 h = self . h h1 = h + 1 w2 = w [ - h1 : ] . reshape ( h1 , 1 ) w1 = w [ : - h1 ] . reshape ( i1 , h ) if sparse . issparse ( x0 ) : x0 = x0 . tocsr ( ) [ idx0 ] x1 = x1 . tocsr ( ) [ idx1 ] xb0 = sparse . hstack ( ( x0 , b ) ) xb1 = sparse . hstack ( ( x1 , b ) ) else : x0 = x0 [ idx0 ] x1 = x1 [ idx1 ] xb0 = np . hstack ( ( x0 , b ) ) xb1 = np . hstack ( ( x1 , b ) ) z0 = np . hstack ( ( sigm ( xb0 . dot ( w1 ) ) , b ) ) z1 = np . hstack ( ( sigm ( xb1 . dot ( w1 ) ) , b ) ) y0 = z0 . dot ( w2 ) y1 = z1 . dot ( w2 ) e = 1 - ( y1 - y0 ) dy = e / n dw1 = - ( xb1 . T . dot ( dy . dot ( w2 [ : - 1 ] . reshape ( 1 , h ) ) * dsigm ( xb1 . dot ( w1 ) ) ) - xb0 . T . dot ( dy . dot ( w2 [ : - 1 ] . reshape ( 1 , h ) ) * dsigm ( xb0 . dot ( w1 ) ) ) ) . reshape ( i1 * h ) + self . l1 * w [ : - h1 ] / ( i1 * h ) dw2 = - ( z1 - z0 ) . T . dot ( dy ) . reshape ( h1 ) + self . l2 * w [ - h1 : ] / h1 return np . append ( dw1 , dw2 ) | Return the derivatives of the cost function for predictions . |
59,194 | def _transform_col ( self , x , col ) : return norm . ppf ( self . ecdfs [ col ] ( x ) * .998 + .001 ) | Normalize one numerical column . |
59,195 | def _get_label_encoder_and_max ( self , x ) : label_count = x . fillna ( NAN_INT ) . value_counts ( ) n_uniq = label_count . shape [ 0 ] label_count = label_count [ label_count >= self . min_obs ] n_uniq_new = label_count . shape [ 0 ] offset = 0 if n_uniq == n_uniq_new else 1 label_encoder = pd . Series ( np . arange ( n_uniq_new ) + offset , index = label_count . index ) max_label = label_encoder . max ( ) label_encoder = label_encoder . to_dict ( ) return label_encoder , max_label | Return a mapping from values and its maximum of a column to integer labels . |
59,196 | def _transform_col ( self , x , i ) : return x . fillna ( NAN_INT ) . map ( self . label_encoders [ i ] ) . fillna ( 0 ) | Encode one categorical column into labels . |
59,197 | def _transform_col ( self , x , i ) : labels = self . label_encoder . _transform_col ( x , i ) label_max = self . label_encoder . label_maxes [ i ] index = np . array ( range ( len ( labels ) ) ) i = index [ labels > 0 ] j = labels [ labels > 0 ] - 1 if len ( i ) > 0 : return sparse . coo_matrix ( ( np . ones_like ( i ) , ( i , j ) ) , shape = ( x . shape [ 0 ] , label_max ) ) else : return None | Encode one categorical column into sparse matrix with one - hot - encoding . |
59,198 | def transform ( self , X ) : for i , col in enumerate ( X . columns ) : X_col = self . _transform_col ( X [ col ] , i ) if X_col is not None : if i == 0 : X_new = X_col else : X_new = sparse . hstack ( ( X_new , X_col ) ) logger . debug ( '{} . format ( col , self . label_encoder . label_maxes [ i ] ) ) return X_new | Encode categorical columns into sparse matrix with one - hot - encoding . |
59,199 | def predict ( self , x ) : if self . _is_leaf ( ) : d1 = self . predict_initialize [ 'count_dict' ] d2 = count_dict ( self . Y ) for key , value in d1 . iteritems ( ) : if key in d2 : d2 [ key ] += value else : d2 [ key ] = value return argmax ( d2 ) else : if self . criterion ( x ) : return self . right . predict ( x ) else : return self . left . predict ( x ) | Make prediction recursively . Use both the samples inside the current node and the statistics inherited from parent . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.