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 .... | 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 ( ret... | 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 . compone... | 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'... | 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 ... | 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' : ele... | 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 init... | 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 S... | 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 ) , 'u... | 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... | 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 vi... | 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 ) ... | 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 ( ',' ) ] ) r... | 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... | 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 ] = s... | 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... | 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 ) ... | 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 , passwor... | 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 ... | 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 . asse... | 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 ... | 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... | 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 ( ) ret... | 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' ... | 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 ) :... | 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... | 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 ... | 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 . w... | 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 : ... | 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 . ad... | 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 t... | 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 ... | 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 ... | 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. +... | 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 ) ) ... | 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 + ... | 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 ( [ ... | 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 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 } ) r... | 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 ) , ( 'symbolicTimeS... | 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 . fin... | 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 ... | 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 . dequ... | 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... | 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 ( ** kwarg... | 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 ( at... | 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 ( ) ... | 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_branc... | 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 sty... | 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 = ... | 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... | 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 ... | 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... | 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 ... | 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 ... | 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 ... | 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.