idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
1,700 | def ck2respth ( argv = None ) : parser = ArgumentParser ( description = 'Convert a ChemKED YAML file to a ReSpecTh XML file.' ) parser . add_argument ( '-i' , '--input' , type = str , required = True , help = 'Input filename (e.g., "file1.xml")' ) parser . add_argument ( '-o' , '--output' , type = str , required = Fals... | Command - line entry point for converting a ChemKED YAML file to a ReSpecTh XML file . | 172 | 23 |
1,701 | def main ( argv = None ) : parser = ArgumentParser ( description = 'Convert between ReSpecTh XML file and ChemKED YAML file ' 'automatically based on file extension.' ) parser . add_argument ( '-i' , '--input' , type = str , required = True , help = 'Input filename (e.g., "file1.yaml" or "file2.xml")' ) parser . add_ar... | General function for converting between ReSpecTh and ChemKED files based on extension . | 571 | 17 |
1,702 | def process_exception ( self , request , exception ) : if request . user and hasattr ( request . user , 'email' ) : request . META [ 'USER' ] = request . user . email | Add user details . | 45 | 4 |
1,703 | def process_response ( self , request , response ) : if response . status_code == 404 and not settings . DEBUG : domain = request . get_host ( ) path = request . get_full_path ( ) referer = force_text ( request . META . get ( 'HTTP_REFERER' , '' ) , errors = 'replace' ) if not self . is_ignorable_request ( request , pa... | Send broken link emails for relevant 404 NOT FOUND responses . | 296 | 12 |
1,704 | def is_internal_request ( self , domain , referer ) : # Different subdomains are treated as different domains. return bool ( re . match ( "^https?://%s/" % re . escape ( domain ) , referer ) ) | Returns True if referring URL is the same domain as current request . | 53 | 13 |
1,705 | def parse ( self , representation ) : elements = extract_tokens ( representation ) try : scales = [ DurationRepresentation ( float ( p [ 0 ] ) , Scale ( p [ 1 ] ) ) for p in elements ] except ValueError : raise ScaleFormatError ( "Malformed duration representation: {0}" . format ( representation ) ) return scales | Parses a duration string representation | 74 | 7 |
1,706 | def get_or_create_from_ip ( ip ) : data = ip_api_handler . get ( ip ) if data and any ( v for v in data . values ( ) ) : if data . get ( 'ip_address' , None ) is None or not data [ 'ip_address' ] : data [ 'ip_address' ] = ip return IPInfo . objects . get_or_create ( * * data ) return None , False | Get or create an entry using obtained information from an IP . | 98 | 12 |
1,707 | def update_ip_info ( self , since_days = 10 , save = False , force = False ) : # If ip already checked try : last_check = IPInfoCheck . objects . get ( ip_address = self . client_ip_address ) # If checked less than since_days ago, don't check again since_last = datetime . date . today ( ) - last_check . date if since_l... | Update the IP info . | 320 | 5 |
1,708 | def start_daemon ( ) : if RequestLog . daemon is None : parser = get_nginx_parser ( ) RequestLog . daemon = RequestLog . ParseToDBThread ( parser , daemon = True ) RequestLog . daemon . start ( ) return RequestLog . daemon | Start a thread to continuously read log files and append lines in DB . | 59 | 14 |
1,709 | def from_respecth ( cls , filename_xml , file_author = '' , file_author_orcid = '' ) : properties = ReSpecTh_to_ChemKED ( filename_xml , file_author , file_author_orcid , validate = False ) return cls ( dict_input = properties ) | Construct a ChemKED instance directly from a ReSpecTh file . | 70 | 14 |
1,710 | def validate_yaml ( self , properties ) : validator = OurValidator ( schema ) if not validator . validate ( properties ) : for key , value in validator . errors . items ( ) : if any ( [ 'unallowed value' in v for v in value ] ) : print ( ( '{key} has an illegal value. Allowed values are {values} and are case ' 'sensiti... | Validate the parsed YAML file for adherance to the ChemKED format . | 118 | 19 |
1,711 | def write_file ( self , filename , * , overwrite = False ) : # Ensure file isn't already present if exists ( filename ) and not overwrite : raise OSError ( filename + ' already present. Specify "overwrite=True" ' 'to overwrite, or rename.' ) with open ( filename , 'w' ) as yaml_file : yaml . dump ( self . _properties ,... | Write new ChemKED YAML file based on object . | 91 | 13 |
1,712 | def process_quantity ( self , properties ) : quant = Q_ ( properties [ 0 ] ) if len ( properties ) > 1 : unc = properties [ 1 ] uncertainty = unc . get ( 'uncertainty' , False ) upper_uncertainty = unc . get ( 'upper-uncertainty' , False ) lower_uncertainty = unc . get ( 'lower-uncertainty' , False ) uncertainty_type =... | Process the uncertainty information from a given quantity and return it | 458 | 11 |
1,713 | def get_cantera_composition_string ( self , species_conversion = None ) : if self . composition_type in [ 'mole fraction' , 'mass fraction' ] : factor = 1.0 elif self . composition_type == 'mole percent' : factor = 100.0 else : raise ValueError ( 'Unknown composition type: {}' . format ( self . composition_type ) ) if ... | Get the composition in a string format suitable for input to Cantera . | 395 | 14 |
1,714 | def get_cantera_mole_fraction ( self , species_conversion = None ) : if self . composition_type == 'mass fraction' : raise ValueError ( 'Cannot get mole fractions from the given composition.\n' '{}' . format ( self . composition ) ) else : return self . get_cantera_composition_string ( species_conversion ) | Get the mole fractions in a string format suitable for input to Cantera . | 84 | 15 |
1,715 | def get_cantera_mass_fraction ( self , species_conversion = None ) : if self . composition_type in [ 'mole fraction' , 'mole percent' ] : raise ValueError ( 'Cannot get mass fractions from the given composition.\n' '{}' . format ( self . composition ) ) else : return self . get_cantera_composition_string ( species_conv... | Get the mass fractions in a string format suitable for input to Cantera . | 92 | 15 |
1,716 | def lockfile ( lockfile_name , lock_wait_timeout = - 1 ) : def decorator ( func ) : @ wraps ( func ) def wrapper ( * args , * * kwargs ) : lock = FileLock ( lockfile_name ) try : lock . acquire ( lock_wait_timeout ) except AlreadyLocked : return except LockTimeout : return try : result = func ( * args , * * kwargs ) fi... | Only runs the method if the lockfile is not acquired . | 106 | 12 |
1,717 | def get_username ( identifier ) : pattern = re . compile ( '.+@\w+\..+' ) if pattern . match ( identifier ) : try : user = User . objects . get ( email = identifier ) except : raise Http404 else : return user . username else : return identifier | Checks if a string is a email adress or not . | 63 | 13 |
1,718 | def _create_payload ( self , symbols ) : payload = { 'access_key' : self . access_key } if symbols is not None : payload [ 'symbols' ] = ',' . join ( symbols ) return payload | Creates a payload with no none values . | 51 | 9 |
1,719 | def historical_rates ( self , date , symbols = None ) : try : if isinstance ( date , datetime . date ) : # Convert date to ISO 8601 format. date = date . isoformat ( ) symbols = symbols or self . symbols payload = self . _create_payload ( symbols ) url = BASE_URL + date response = requests . get ( url , params = payloa... | Get historical rates for any day since date . | 119 | 9 |
1,720 | def distinct ( l ) : seen = set ( ) seen_add = seen . add return ( _ for _ in l if not ( _ in seen or seen_add ( _ ) ) ) | Return a list where the duplicates have been removed . | 40 | 11 |
1,721 | def iter_format_modules ( lang ) : if check_for_language ( lang ) : format_locations = [ ] for path in CUSTOM_FORMAT_MODULE_PATHS : format_locations . append ( path + '.%s' ) format_locations . append ( 'django.conf.locale.%s' ) locale = to_locale ( lang ) locales = [ locale ] if '_' in locale : locales . append ( loca... | Does the heavy lifting of finding format modules . | 152 | 9 |
1,722 | def get_format_modules ( lang = None , reverse = False ) : if lang is None : lang = get_language ( ) modules = _format_modules_cache . setdefault ( lang , list ( iter_format_modules ( lang ) ) ) if reverse : return list ( reversed ( modules ) ) return modules | Returns a list of the format modules found | 67 | 8 |
1,723 | def as_view ( cls , * * initkwargs ) : # sanitize keyword arguments for key in initkwargs : if key in cls . http_method_names : raise TypeError ( "You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % ( key , cls . __name__ ) ) if not hasattr ( cls , key ) : raise TypeError ( "%s()... | Main entry point for a request - response process . | 376 | 10 |
1,724 | def context ( self ) : stats = status_codes_by_date_stats ( ) attacks_data = [ { 'type' : 'line' , 'zIndex' : 9 , 'name' : _ ( 'Attacks' ) , 'data' : [ ( v [ 0 ] , v [ 1 ] [ 'attacks' ] ) for v in stats ] } ] codes_data = [ { 'zIndex' : 4 , 'name' : '2xx' , 'data' : [ ( v [ 0 ] , v [ 1 ] [ 200 ] ) for v in stats ] } , ... | Get the context . | 312 | 4 |
1,725 | def widgets ( self ) : widgets = [ ] for i , chart in enumerate ( most_visited_pages_charts ( ) ) : widgets . append ( Widget ( html_id = 'most_visited_chart_%d' % i , content = json . dumps ( chart ) , template = 'meerkat/widgets/highcharts.html' , js_code = [ 'plotOptions.tooltip.pointFormatter' ] ) ) return widgets | Get the items . | 103 | 4 |
1,726 | def get ( self , str_representation ) : for scale in self . SCALES : if str_representation in scale : return scale raise ScaleFormatError ( "Unsupported scale format: {0}" . format ( str_representation ) ) | Retrieves a scale representation from it s string representation | 53 | 11 |
1,727 | def valid_token ( token ) : is_scale = False # Check if the token represents a scale # If it doesn't set a flag accordingly try : Scale ( token ) is_scale = True except ScaleFormatError : pass # If token either represents a numerical value, a # separator token, or a scale, it is considered valid if any ( [ token . isdi... | Asserts a provided string is a valid duration token representation | 101 | 12 |
1,728 | def extract_tokens ( representation , separators = SEPARATOR_CHARACTERS ) : buff = "" elements = [ ] last_index = 0 last_token = None for index , c in enumerate ( representation ) : # if separator character is found, push # the content of the buffer in the elements list if c in separators : if buff : # If the last foun... | Extracts durations tokens from a duration representation . | 284 | 11 |
1,729 | def create_random_string ( length = 7 , chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789' , repetitions = False ) : if repetitions : return '' . join ( random . choice ( chars ) for _ in range ( length ) ) return '' . join ( random . sample ( chars , length ) ) | Returns a random string based on the provided arguments . | 77 | 10 |
1,730 | def load_member ( fqn ) : modulename , member_name = split_fqn ( fqn ) module = __import__ ( modulename , globals ( ) , locals ( ) , member_name ) return getattr ( module , member_name ) | Loads and returns a class for a given fully qualified name . | 61 | 13 |
1,731 | def split_fqn ( fqn ) : if hasattr ( fqn , '__call__' ) : fqn_string = fqn ( ) else : fqn_string = fqn return fqn_string . rsplit ( '.' , 1 ) | Returns the left and right part of the import . | 64 | 10 |
1,732 | def send ( self , data ) : self . logger . debug ( 'Send data: {}' . format ( data ) ) if not self . connected : self . logger . warning ( 'Connection not established. Return...' ) return self . websocket . send ( json . dumps ( data ) ) | Sends data to the server . | 62 | 7 |
1,733 | def _on_message ( self , socket , message ) : data = json . loads ( message ) message_type = None identifier = None subscription = None if 'type' in data : message_type = data [ 'type' ] if 'identifier' in data : identifier = json . loads ( data [ 'identifier' ] ) if identifier is not None : subscription = self . find_... | Called aways when a message arrives . | 203 | 9 |
1,734 | def _on_close ( self , socket ) : self . logger . debug ( 'Connection closed.' ) for subscription in self . subscriptions . values ( ) : if subscription . state == 'subscribed' : subscription . state = 'connection_pending' | Called when the connection was closed . | 53 | 8 |
1,735 | def connected ( self ) : return self . websocket is not None and self . websocket . sock is not None and self . websocket . sock . connected | If connected to server . | 33 | 5 |
1,736 | def find_subscription ( self , identifier ) : for subscription in self . subscriptions . values ( ) : if subscription . identifier == identifier : return subscription | Finds a subscription by it s identifier . | 31 | 9 |
1,737 | def create ( self ) : self . logger . debug ( 'Create subscription on server...' ) if not self . connection . connected : self . state = 'connection_pending' return data = { 'command' : 'subscribe' , 'identifier' : self . _identifier_string ( ) } self . connection . send ( data ) self . state = 'pending' | Subscribes at the server . | 82 | 7 |
1,738 | def remove ( self ) : self . logger . debug ( 'Remove subscription from server...' ) data = { 'command' : 'unsubscribe' , 'identifier' : self . _identifier_string ( ) } self . connection . send ( data ) self . state = 'unsubscribed' | Removes the subscription . | 65 | 5 |
1,739 | def send ( self , message ) : self . logger . debug ( 'Send message: {}' . format ( message ) ) if self . state == 'pending' or self . state == 'connection_pending' : self . logger . info ( 'Connection not established. Add message to queue.' ) self . message_queue . append ( message ) return elif self . state == 'unsub... | Sends data to the server on the subscription channel . | 157 | 11 |
1,740 | def received ( self , data ) : self . logger . debug ( 'Data received: {}' . format ( data ) ) message_type = None if 'type' in data : message_type = data [ 'type' ] if message_type == 'confirm_subscription' : self . _subscribed ( ) elif message_type == 'reject_subscription' : self . _rejected ( ) elif self . receive_c... | API for the connection to forward information to this subscription instance . | 143 | 12 |
1,741 | def _subscribed ( self ) : self . logger . debug ( 'Subscription confirmed.' ) self . state = 'subscribed' for message in self . message_queue : self . send ( message ) | Called when the subscription was accepted successfully . | 43 | 9 |
1,742 | def cli_opts ( ) : parser = argparse . ArgumentParser ( ) parser . add_argument ( "--homeassistant-config" , type = str , required = False , dest = "config" , help = "Create configuration section for home assistant" , ) parser . add_argument ( "-f" , "--filter" , type = str , required = False , dest = "filter" , help =... | Handle the command line options | 199 | 5 |
1,743 | def _setup_signal_handler ( self ) : signal . signal ( signal . SIGTERM , self . _signal_handler ) signal . signal ( signal . SIGINT , self . _signal_handler ) signal . signal ( signal . SIGQUIT , self . _signal_handler ) | Register signal handlers | 65 | 3 |
1,744 | def _signal_handler ( self , signum , frame ) : if self . _options . config : with open ( self . _options . config , "w" ) as cfg : yaml . dump ( self . _home_assistant_config ( ) , cfg ) print ( "Dumped home assistant configuration at" , self . _options . config ) self . _connection . close ( ) sys . exit ( 0 ) | Method called when handling signals | 93 | 5 |
1,745 | def start ( self ) : print ( "Entering monitoring mode, press CTRL-C to quit" ) serial = self . _connection . serial while True : serial . write ( b"@R" ) length = int ( serial . read ( ) , 16 ) data = serial . read ( length * 2 ) message = messages . parse ( data ) if not ( self . _options . filter and message . entit... | Monitor the bus for events and handle them | 197 | 8 |
1,746 | def _add_device ( self , scs_id , ha_id , name ) : if scs_id in self . _devices : return self . _devices [ scs_id ] = { 'name' : name , 'ha_id' : ha_id } | Add device to the list of known ones | 60 | 8 |
1,747 | def _home_assistant_config ( self ) : devices = { } for scs_id , dev in self . _devices . items ( ) : devices [ dev [ 'ha_id' ] ] = { 'name' : dev [ 'name' ] , 'scs_id' : scs_id } return { 'devices' : devices } | Creates home assistant configuration for the known devices | 77 | 9 |
1,748 | def _load_filter ( self , config ) : path = pathlib . Path ( config ) if not path . is_file ( ) : return with open ( config , 'r' ) as conf : devices = yaml . load ( conf ) [ 'devices' ] for ha_id , dev in devices . items ( ) : self . _devices [ dev [ 'scs_id' ] ] = { ha_id : dev , 'name' : dev [ 'name' ] } | Load the filter file and populates self . _devices accordingly | 104 | 12 |
1,749 | def close ( self ) : self . _serial . write ( b"@c" ) self . _serial . read ( ) self . _serial . close ( ) | Closes the connection to the serial port and ensure no pending operatoin are left | 35 | 17 |
1,750 | def load ( self , value ) : if self . property_type is None : return value elif not isinstance ( self . property_type , BaseType ) : raise TypeError ( 'property_type must be schematics BaseType' ) else : native_value = self . property_type . to_native ( value ) self . property_type . validate ( native_value ) return na... | Load a value converting it to the proper type if validation_type exists . | 84 | 15 |
1,751 | def _update_property_keys ( cls ) : for attr_name , config_prop in cls . _iter_config_props ( ) : if config_prop . property_key is None : config_prop . property_key = attr_name | Set unspecified property_keys for each ConfigProperty to the name of the class attr | 58 | 17 |
1,752 | def _set_instance_prop ( self , attr_name , config_prop , value ) : setattr ( self , attr_name , value ) # add to varz if it is not private if not config_prop . exclude_from_varz : self . varz [ attr_name ] = value | Set instance property to a value and add it varz if needed | 69 | 13 |
1,753 | def _load ( self ) : for attr_name , config_prop in self . _iter_config_props ( ) : found = False for loader in self . _loaders : if loader . exists ( config_prop . property_key ) : raw_value = loader . get ( config_prop . property_key ) converted_value = config_prop . load ( raw_value ) self . _set_instance_prop ( att... | Load values for all ConfigProperty attributes | 178 | 7 |
1,754 | def in_same_dir ( as_file , target_file ) : return os . path . abspath ( os . path . join ( os . path . dirname ( as_file ) , target_file ) ) | Return an absolute path to a target file that is located in the same directory as as_file | 47 | 19 |
1,755 | def compare_name ( given_name , family_name , question_name ) : # lowercase everything given_name = given_name . lower ( ) family_name = family_name . lower ( ) question_name = question_name . lower ( ) # rearrange names given as "last, first middle" if ',' in question_name : name_split = question_name . split ( ',' ) ... | Compares a name in question to a specified name separated into given and family . | 701 | 16 |
1,756 | def _validate_isvalid_history ( self , isvalid_history , field , value ) : # Check the type has appropriate units history_type = value [ 'type' ] if history_type . endswith ( 'emission' ) : history_type = 'emission' elif history_type . endswith ( 'absorption' ) : history_type = 'absorption' quantity = 1.0 * ( units ( v... | Checks that the given time history is properly formatted . | 380 | 11 |
1,757 | def _validate_isvalid_quantity ( self , isvalid_quantity , field , value ) : quantity = Q_ ( value [ 0 ] ) low_lim = 0.0 * units ( property_units [ field ] ) try : if quantity <= low_lim : self . _error ( field , 'value must be greater than 0.0 {}' . format ( property_units [ field ] ) , ) except pint . DimensionalityE... | Checks for valid given value and appropriate units . | 124 | 10 |
1,758 | def _validate_isvalid_uncertainty ( self , isvalid_uncertainty , field , value ) : self . _validate_isvalid_quantity ( True , field , value ) # This len check is necessary for reasons that aren't quite clear to me # Cerberus calls this validation method even when lists have only one element # and should therefore be va... | Checks for valid given value and appropriate units with uncertainty . | 263 | 12 |
1,759 | def _validate_isvalid_orcid ( self , isvalid_orcid , field , value ) : if isvalid_orcid and 'ORCID' in value : try : res = search_orcid ( value [ 'ORCID' ] ) except ConnectionError : warn ( 'network not available, ORCID not validated.' ) return except HTTPError : self . _error ( field , 'ORCID incorrect or invalid for ... | Checks for valid ORCID if given . | 226 | 10 |
1,760 | def _validate_isvalid_composition ( self , isvalid_composition , field , value ) : sum_amount = 0.0 if value [ 'kind' ] in [ 'mass fraction' , 'mole fraction' ] : low_lim = 0.0 up_lim = 1.0 total_amount = 1.0 elif value [ 'kind' ] in [ 'mole percent' ] : low_lim = 0.0 up_lim = 100.0 total_amount = 100.0 else : self . _... | Checks for valid specification of composition . | 377 | 8 |
1,761 | def convert_types_slow ( df ) : dtypes = get_types ( df ) for k , v in dtypes . items ( ) : t = df [ df [ 'key' ] == k ] t [ 'value' ] = t [ 'value' ] . astype ( v ) df = df . apply ( convert_row , axis = 1 ) return df | This is a slow operation . | 79 | 6 |
1,762 | def plot_all ( * args , * * kwargs ) : dfs = do_all ( * args , * * kwargs ) ps = [ ] for line in dfs : f , df , config = line df . plot ( title = config [ 'name' ] ) ps . append ( df ) return ps | Read all the trial data and plot the result of applying a function on them . | 69 | 16 |
1,763 | def serialize ( v , known_modules = [ ] ) : tname = name ( v , known_modules = known_modules ) func = serializer ( tname ) return func ( v ) , tname | Get a text representation of an object . | 45 | 8 |
1,764 | def deserialize ( type_ , value = None , * * kwargs ) : if not isinstance ( type_ , str ) : return type_ des = deserializer ( type_ , * * kwargs ) if value is None : return des return des ( value ) | Get an object from a text representation | 60 | 7 |
1,765 | def content ( self ) : if self . _content is None : self . _content = self . parse_files ( ) return self . _content | Return parsed data . Parse it if not already parsed . | 31 | 12 |
1,766 | def parse_files ( self ) : log_re = self . log_format_regex log_lines = [ ] for log_file in self . matching_files ( ) : with open ( log_file ) as f : matches = re . finditer ( log_re , f . read ( ) ) for match in matches : log_lines . append ( match . groupdict ( ) ) return log_lines | Find the files and parse them . | 88 | 7 |
1,767 | def serialize_distribution ( network_agents , known_modules = [ ] ) : d = deepcopy ( list ( network_agents ) ) for v in d : if 'threshold' in v : del v [ 'threshold' ] v [ 'agent_type' ] = serialize_type ( v [ 'agent_type' ] , known_modules = known_modules ) return d | When serializing an agent distribution remove the thresholds in order to avoid cluttering the YAML definition file . | 85 | 22 |
1,768 | def _validate_states ( states , topology ) : states = states or [ ] if isinstance ( states , dict ) : for x in states : assert x in topology . node else : assert len ( states ) <= len ( topology ) return states | Validate states to avoid ignoring states during initialization | 55 | 9 |
1,769 | def _convert_agent_types ( ind , to_string = False , * * kwargs ) : if to_string : return serialize_distribution ( ind , * * kwargs ) return deserialize_distribution ( ind , * * kwargs ) | Convenience method to allow specifying agents by class or class name . | 60 | 14 |
1,770 | def _agent_from_distribution ( distribution , value = - 1 , agent_id = None ) : if value < 0 : value = random . random ( ) for d in sorted ( distribution , key = lambda x : x [ 'threshold' ] ) : threshold = d [ 'threshold' ] # Check if the definition matches by id (first) or by threshold if not ( ( agent_id is not None... | Used in the initialization of agents given an agent distribution . | 187 | 11 |
1,771 | def launch ( self , port = None ) : if port is not None : self . port = port url = 'http://127.0.0.1:{PORT}' . format ( PORT = self . port ) print ( 'Interface starting at {url}' . format ( url = url ) ) self . listen ( self . port ) # webbrowser.open(url) tornado . ioloop . IOLoop . instance ( ) . start ( ) | Run the app . | 98 | 4 |
1,772 | def status_codes_by_date_stats ( ) : def date_counter ( queryset ) : return dict ( Counter ( map ( lambda dt : ms_since_epoch ( datetime . combine ( make_naive ( dt ) , datetime . min . time ( ) ) ) , list ( queryset . values_list ( 'datetime' , flat = True ) ) ) ) ) codes = { low : date_counter ( RequestLog . objects ... | Get stats for status codes by date . | 325 | 8 |
1,773 | def enter ( self , pub_id , * nodes ) : try : pub = self [ 'pubs' ] [ pub_id ] except KeyError : raise ValueError ( 'Pub {} is not available' . format ( pub_id ) ) if not pub [ 'open' ] or ( pub [ 'capacity' ] < ( len ( nodes ) + pub [ 'occupancy' ] ) ) : return False pub [ 'occupancy' ] += len ( nodes ) for node in no... | Agents will try to enter . The pub checks if it is possible | 116 | 14 |
1,774 | def exit ( self , pub_id , * node_ids ) : try : pub = self [ 'pubs' ] [ pub_id ] except KeyError : raise ValueError ( 'Pub {} is not available' . format ( pub_id ) ) for node_id in node_ids : node = self . get_agent ( node_id ) if pub_id == node [ 'pub' ] : del node [ 'pub' ] pub [ 'occupancy' ] -= 1 | Agents will notify the pub they want to leave | 103 | 10 |
1,775 | def looking_for_friends ( self ) : self . info ( 'I am looking for friends' ) available_friends = list ( self . get_agents ( drunk = False , pub = None , state_id = self . looking_for_friends . id ) ) if not available_friends : self . info ( 'Life sucks and I\'m alone!' ) return self . at_home befriended = self . try_f... | Look for friends to drink with | 108 | 6 |
1,776 | def looking_for_pub ( self ) : if self [ 'pub' ] != None : return self . sober_in_pub self . debug ( 'I am looking for a pub' ) group = list ( self . get_neighboring_agents ( ) ) for pub in self . env . available_pubs ( ) : self . debug ( 'We\'re trying to get into {}: total: {}' . format ( pub , len ( group ) ) ) if s... | Look for a pub that accepts me and my friends | 149 | 10 |
1,777 | def befriend ( self , other_agent , force = False ) : if force or self [ 'openness' ] > random ( ) : self . env . add_edge ( self , other_agent ) self . info ( 'Made some friend {}' . format ( other_agent ) ) return True return False | Try to become friends with another agent . The chances of success depend on both agents openness . | 65 | 18 |
1,778 | def try_friends ( self , others ) : befriended = False k = int ( 10 * self [ 'openness' ] ) shuffle ( others ) for friend in islice ( others , k ) : # random.choice >= 3.7 if friend == self : continue if friend . befriend ( self ) : self . befriend ( friend , force = True ) self . debug ( 'Hooray! new friend: {}' . for... | Look for random agents around me and try to befriend them | 129 | 11 |
1,779 | def profile_distribution ( data ) : if len ( data ) == 0 : return ( data , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan , np . nan ) else : ddof = 1 if len ( data ) > 1 else 0 dist_mean = np . mean ( data ) dist_stdev = np . std ( data , ddof = ddof ) dist_min , dist_quartile1 ,... | Compute the mean standard deviation min quartile1 quartile2 quartile3 and max of a vector | 216 | 21 |
1,780 | def to_native ( self , value ) : if isinstance ( value , dict ) : return value elif isinstance ( value , six . string_types ) : native_value = json . loads ( value ) if isinstance ( native_value , dict ) : return native_value else : raise ConversionError ( u'Cannot load value as a dict: {}' . format ( value ) ) | Return the value as a dict raising error if conversion to dict is not possible | 84 | 15 |
1,781 | def to_native ( self , value ) : if isinstance ( value , six . string_types ) : value_list = value . split ( self . string_delim ) else : value_list = value to_native = self . member_type . to_native if self . member_type is not None else lambda x : x return [ to_native ( item ) for item in value_list ] | Load a value as a list converting items if necessary | 87 | 10 |
1,782 | def validate_member_type ( self , value ) : if self . member_type : for item in value : self . member_type . validate ( item ) | Validate each member of the list if member_type exists | 34 | 12 |
1,783 | def validate_length ( self , value ) : list_len = len ( value ) if value else 0 if self . max_length is not None and list_len > self . max_length : raise ValidationError ( u'List has {} values; max length is {}' . format ( list_len , self . max_length ) ) if self . min_length is not None and list_len < self . min_lengt... | Validate the length of value if min_length or max_length was specified | 124 | 16 |
1,784 | def validate_resource ( self , value ) : def do_backoff ( * args , * * kwargs ) : """Call self._test_connection with exponential backoff, for self._max_tries attempts""" attempts = 0 while True : try : self . _test_connection ( * args , * * kwargs ) break except ValidationError : wait_secs = min ( self . _max_wait , 2 ... | Validate the network resource with exponential backoff | 128 | 9 |
1,785 | def list_metafeatures ( cls , group = "all" ) : # todo make group for intractable metafeatures for wide datasets or # datasets with high cardinality categorical columns: # PredPCA1, PredPCA2, PredPCA3, PredEigen1, PredEigen2, PredEigen3, # PredDet, kNN1NErrRate, kNN1NKappa, LinearDiscriminantAnalysisKappa, # LinearDisc... | Returns a list of metafeatures computable by the Metafeatures class . | 225 | 16 |
1,786 | def _sample_rows ( self , X , Y , sample_shape , seed ) : if sample_shape [ 0 ] is None or X . shape [ 0 ] <= sample_shape [ 0 ] : X_sample , Y_sample = X , Y elif Y is None : np . random . seed ( seed ) row_indices = np . random . choice ( X . shape [ 0 ] , size = sample_shape [ 0 ] , replace = False ) X_sample , Y_sa... | Stratified uniform sampling of rows according to the classes in Y . Ensures there are enough samples from each class in Y for cross validation . | 244 | 29 |
1,787 | def _fetch_secrets ( vault_url , path , token ) : url = _url_joiner ( vault_url , 'v1' , path ) resp = requests . get ( url , headers = VaultLoader . _get_headers ( token ) ) resp . raise_for_status ( ) data = resp . json ( ) if data . get ( 'errors' ) : raise VaultException ( u'Error fetching Vault secrets from path {... | Read data from the vault path | 120 | 6 |
1,788 | def _fetch_app_role_token ( vault_url , role_id , secret_id ) : url = _url_joiner ( vault_url , 'v1/auth/approle/login' ) resp = requests . post ( url , data = { 'role_id' : role_id , 'secret_id' : secret_id } ) resp . raise_for_status ( ) data = resp . json ( ) if data . get ( 'errors' ) : raise VaultException ( u'Err... | Get a Vault token using the RoleID and SecretID | 145 | 11 |
1,789 | def reload ( self ) : self . _source = self . _fetch_secrets ( self . _vault_url , self . _path , self . _token ) | Reread secrets from the vault path | 38 | 8 |
1,790 | def sorted_options ( sort_options ) : return [ { 'title' : v [ 'title' ] , 'value' : ( '-{0}' . format ( k ) if v . get ( 'default_order' , 'asc' ) == 'desc' else k ) , } for k , v in sorted ( sort_options . items ( ) , key = lambda x : x [ 1 ] . get ( 'order' , 0 ) ) ] | Sort sort options for display . | 99 | 6 |
1,791 | def html_to_plain_text ( html ) : # Use BeautifulSoup to normalize the html soup = BeautifulSoup ( html , "html.parser" ) # Init the parser parser = HTML2PlainParser ( ) parser . feed ( str ( soup . encode ( 'utf-8' ) ) ) # Strip the end of the plain text result = parser . text . rstrip ( ) # Add footnotes if parser . ... | Converts html code into formatted plain text . | 134 | 9 |
1,792 | def handle_data ( self , data ) : # Only proceed with unignored elements if self . lasttag not in self . ignored_elements : # Remove any predefined linebreaks text = data . replace ( '\n' , '' ) # If there's some text left, proceed! if text : if self . lasttag == 'li' : # Use a special prefix for list elements self . t... | Handles data between tags . | 130 | 6 |
1,793 | def run ( self ) : task = None monitor_task = MonitorTask ( notification_endpoint = self . _handle_message ) while True : if self . _terminate : self . _logger . info ( "scsgate.Reactor exiting" ) self . _connection . close ( ) break try : task = self . _request_queue . get_nowait ( ) self . _logger . debug ( "scsgate.... | Starts the thread | 147 | 4 |
1,794 | def mygenerator ( n = 5 , n_edges = 5 ) : G = nx . Graph ( ) for i in range ( n ) : G . add_node ( i ) for i in range ( n_edges ) : nodes = list ( G . nodes ) n_in = choice ( nodes ) nodes . remove ( n_in ) # Avoid loops n_out = choice ( nodes ) G . add_edge ( n_in , n_out ) return G | Just a simple generator that creates a network with n nodes and n_edges edges . Edges are assigned randomly only avoiding self loops . | 103 | 28 |
1,795 | def insert_files ( self , rootpath , directoryInFilter = None , directoryExFilter = None , compileInFilter = None , compileExFilter = None , contentInFilter = None , contentExFilter = None ) : # Overrides directoryInFilter = self . DirectoryInFilter if directoryInFilter is None else directoryInFilter directoryExFilter ... | Inserts files by recursive traversing the rootpath and inserting files according the addition filter parameters . | 446 | 19 |
1,796 | def encode_caveat ( condition , root_key , third_party_info , key , ns ) : if third_party_info . version == VERSION_1 : return _encode_caveat_v1 ( condition , root_key , third_party_info . public_key , key ) if ( third_party_info . version == VERSION_2 or third_party_info . version == VERSION_3 ) : return _encode_cavea... | Encrypt a third - party caveat . | 161 | 8 |
1,797 | def _encode_caveat_v1 ( condition , root_key , third_party_pub_key , key ) : plain_data = json . dumps ( { 'RootKey' : base64 . b64encode ( root_key ) . decode ( 'ascii' ) , 'Condition' : condition } ) box = nacl . public . Box ( key . key , third_party_pub_key . key ) encrypted = box . encrypt ( six . b ( plain_data )... | Create a JSON - encoded third - party caveat . | 251 | 10 |
1,798 | def _encode_caveat_v2_v3 ( version , condition , root_key , third_party_pub_key , key , ns ) : ns_data = bytearray ( ) if version >= VERSION_3 : ns_data = ns . serialize_text ( ) data = bytearray ( ) data . append ( version ) data . extend ( third_party_pub_key . serialize ( raw = True ) [ : _PUBLIC_KEY_PREFIX_LEN ] ) ... | Create a version 2 or version 3 third - party caveat . | 252 | 12 |
1,799 | def _encode_secret_part_v2_v3 ( version , condition , root_key , ns ) : data = bytearray ( ) data . append ( version ) encode_uvarint ( len ( root_key ) , data ) data . extend ( root_key ) if version >= VERSION_3 : encode_uvarint ( len ( ns ) , data ) data . extend ( ns ) data . extend ( condition . encode ( 'utf-8' ) ... | Creates a version 2 or version 3 secret part of the third party caveat . The returned data is not encrypted . | 110 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.