idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
14,900 | def run ( self ) : input = self . _consume ( ) put_item = self . _que_out . put try : if input is None : res = self . _callable ( * self . _args , ** self . _kwargs ) else : res = self . _callable ( input , * self . _args , ** self . _kwargs ) if res != None : for item in res : put_item ( item ) except Exception as e : self . _que_err . put ( ( self . name , e ) ) if input is not None : for i in input : pass raise finally : for i in range ( self . _num_followers ) : put_item ( EXIT ) self . _que_err . put ( EXIT ) | Execute the task on all the input and send the needed number of EXIT at the end |
14,901 | def setup ( self , workers = 1 , qsize = 0 ) : if workers <= 0 : raise ValueError ( "workers have to be greater then zero" ) if qsize < 0 : raise ValueError ( "qsize have to be greater or equal zero" ) self . qsize = qsize self . workers = workers return self | Setup the pool parameters like number of workers and output queue size |
14,902 | def processes ( self ) : if self . _processes is None : self . _processes = [ ] for p in range ( self . workers ) : t = Task ( self . _target , self . _args , self . _kwargs ) t . name = "%s-%d" % ( self . target_name , p ) self . _processes . append ( t ) return self . _processes | Initialise and return the list of processes associated with this pool |
14,903 | def results ( self ) : tt = None for i , tf in enumerate ( self [ : - 1 ] ) : tt = self [ i + 1 ] q = Queue ( tf . qsize ) tf . set_out ( q , tt . workers ) tt . set_in ( q , tf . workers ) if tt is None : tt = self [ 0 ] q = Queue ( tt . qsize ) err_q = Queue ( ) tt . set_out ( q , 1 ) for t in self : t . set_err ( err_q ) t . _start ( ) for item in iterqueue ( q , tt . workers ) : yield item errors = list ( iterqueue ( err_q , sum ( t . workers for t in self ) ) ) for t in self : t . _join ( ) if len ( errors ) > 0 : task_name , ex = errors [ 0 ] if len ( errors ) == 1 : msg = 'The task "%s" raised %s' % ( task_name , repr ( ex ) , ) else : msg = '%d tasks raised an exeption. First error reported on task "%s": %s' % ( len ( errors ) , task_name , repr ( ex ) ) raise TaskException ( msg ) | Start all the tasks and return data on an iterator |
14,904 | def office_content ( self , election_day , office ) : from electionnight . models import PageType office_type = ContentType . objects . get_for_model ( office ) page_type = PageType . objects . get ( model_type = office_type , election_day = election_day , division_level = office . division . level , ) page_content = self . get ( content_type__pk = office_type . pk , object_id = office . pk , election_day = election_day , ) page_type_content = self . get ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election_day , ) return { "site" : self . site_content ( election_day ) [ "site" ] , "page_type" : self . serialize_content_blocks ( page_type_content ) , "page" : self . serialize_content_blocks ( page_content ) , } | Return serialized content for an office page . |
14,905 | def body_content ( self , election_day , body , division = None ) : from electionnight . models import PageType body_type = ContentType . objects . get_for_model ( body ) page_type = PageType . objects . get ( model_type = body_type , election_day = election_day , body = body , jurisdiction = body . jurisdiction , division_level = body . jurisdiction . division . level , ) page_type_content = self . get ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election_day , ) kwargs = { "content_type__pk" : body_type . pk , "object_id" : body . pk , "election_day" : election_day , } if division : kwargs [ "division" ] = division content = self . get ( ** kwargs ) return { "site" : self . site_content ( election_day ) [ "site" ] , "page_type" : self . serialize_content_blocks ( page_type_content ) , "page" : self . serialize_content_blocks ( content ) , "featured" : [ e . meta . ap_election_id for e in content . featured . all ( ) ] , } | Return serialized content for a body page . |
14,906 | def division_content ( self , election_day , division , special = False ) : from electionnight . models import PageType division_type = ContentType . objects . get_for_model ( division ) page_type = PageType . objects . get ( model_type = division_type , election_day = election_day , division_level = division . level , ) page_content = self . get ( content_type__pk = division_type . pk , object_id = division . pk , election_day = election_day , special_election = special , ) page_type_content = self . get ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election_day , ) return { "site" : self . site_content ( election_day ) [ "site" ] , "page_type" : self . serialize_content_blocks ( page_type_content ) , "page" : self . serialize_content_blocks ( page_content ) , } | Return serialized content for a division page . |
14,907 | def site_content ( self , election_day ) : from electionnight . models import PageType page_type = PageType . objects . get ( model_type = ContentType . objects . get ( app_label = "election" , model = "electionday" ) , election_day = election_day , ) site_content = self . get ( content_type = ContentType . objects . get_for_model ( page_type ) , object_id = page_type . pk , election_day = election_day , ) return { "site" : self . serialize_content_blocks ( site_content ) } | Site content represents content for the entire site on a given election day . |
14,908 | def get_interesting_members ( base_class , cls ) : base_members = dir ( base_class ) predicate = inspect . ismethod if _py2 else inspect . isfunction all_members = inspect . getmembers ( cls , predicate = predicate ) return [ member for member in all_members if not member [ 0 ] in base_members and ( ( hasattr ( member [ 1 ] , "__self__" ) and not member [ 1 ] . __self__ in inspect . getmro ( cls ) ) if _py2 else True ) and not member [ 0 ] . startswith ( "_" ) and not member [ 0 ] . startswith ( "before_" ) and not member [ 0 ] . startswith ( "after_" ) ] | Returns a list of methods that can be routed to |
14,909 | def initialize ( self , value = ( ) ) : if value == ( ) : try : return self . default ( ) except TypeError : return self . default else : return self . clean ( value ) | \ initialize returns a cleaned value or the default raising ValueErrors as necessary . |
14,910 | def clean ( self , value ) : if not isinstance ( value , self . t ) : value = self . t ( value ) if not self . allow_negative and value < 0 : raise ValueError ( 'value was negative' ) if not self . allow_positive and value > 0 : raise ValueError ( 'values was positive' ) return value | clean a value converting and performing bounds checking |
14,911 | def r12_serial_port ( port ) : return serial . Serial ( port , baudrate = BAUD_RATE , parity = PARITY , stopbits = STOP_BITS , bytesize = BYTE_SIZE ) | Create a serial connect to the arm . |
14,912 | def search_for_port ( port_glob , req , expected_res ) : if usb . core . find ( idVendor = 0x0403 , idProduct = 0x6001 ) is None : return None ports = glob . glob ( port_glob ) if len ( ports ) == 0 : return None for port in ports : with r12_serial_port ( port ) as ser : if not ser . isOpen ( ) : ser . open ( ) if sys . version_info [ 0 ] == 2 : ser . write ( str ( req ) . encode ( 'utf-8' ) ) else : ser . write ( bytes ( req , 'utf-8' ) ) time . sleep ( 0.1 ) res = ser . read ( ser . in_waiting ) . decode ( OUTPUT_ENCODING ) if expected_res in res : return port raise ArmException ( 'ST Robotics connection found, but is not responsive.' + ' Is the arm powered on?' ) return None | Find the serial port the arm is connected to . |
14,913 | def connect ( self , port = None ) : if port is None : self . port = search_for_port ( '/dev/ttyUSB*' , 'ROBOFORTH\r\n' , 'ROBOFORTH' ) else : self . port = port if self . port is None : raise ArmException ( 'ST Robotics connection not found.' ) self . ser = r12_serial_port ( port ) if not self . ser . isOpen ( ) : self . ser . open ( ) if not self . ser . isOpen ( ) : raise ArmException ( 'Failed to open serial port. Exiting.' ) return self . port | Open a serial connection to the arm . |
14,914 | def write ( self , text ) : if sys . version_info [ 0 ] == 2 : text_bytes = str ( text . upper ( ) + '\r\n' ) . encode ( 'utf-8' ) else : text_bytes = bytes ( text . upper ( ) + '\r\n' , 'utf-8' ) self . ser . write ( text_bytes ) | Write text out to the arm . |
14,915 | def read ( self , timeout = READ_TIMEOUT , raw = False ) : time . sleep ( READ_SLEEP_TIME ) raw_out = self . ser . read ( self . ser . in_waiting ) out = raw_out . decode ( OUTPUT_ENCODING ) time_waiting = 0 while len ( out ) == 0 or ending_in ( out . strip ( OUTPUT_STRIP_CHARS ) , RESPONSE_END_WORDS ) is None : time . sleep ( READ_SLEEP_TIME ) time_waiting += READ_SLEEP_TIME raw_out += self . ser . read ( self . ser . in_waiting ) out = raw_out . decode ( OUTPUT_ENCODING ) if time_waiting >= timeout : break if raw : return raw_out return out | Read data from the arm . Data is returned as a latin_1 encoded string or raw bytes if raw is True . |
14,916 | def dump ( self , raw = False ) : raw_out = self . ser . read ( self . ser . in_waiting ) if raw : return raw_out return raw_out . decode ( OUTPUT_ENCODING ) | Dump all output currently in the arm s output queue . |
14,917 | def get_info ( self ) : return { 'Connected' : self . is_connected ( ) , 'Port' : self . port , 'Bytes Waiting' : self . ser . in_waiting if self . ser else 0 } | Returns status of the robot arm . |
14,918 | async def get_data ( self ) : try : async with async_timeout . timeout ( 5 , loop = self . _loop ) : response = await self . _session . get ( self . base_url ) _LOGGER . info ( "Response from OpenSenseMap API: %s" , response . status ) self . data = await response . json ( ) _LOGGER . debug ( self . data ) except ( asyncio . TimeoutError , aiohttp . ClientError , socket . gaierror ) : _LOGGER . error ( "Can not load data from openSenseMap API" ) raise exceptions . OpenSenseMapConnectionError | Get details of OpenSenseMap station . |
14,919 | def get_value ( self , key ) : for title in _TITLES . get ( key , ( ) ) + ( key , ) : try : value = [ entry [ 'lastMeasurement' ] [ 'value' ] for entry in self . data [ 'sensors' ] if entry [ 'title' ] == title ] [ 0 ] return value except IndexError : pass return None | Extract a value for a given key . |
14,920 | def cmd ( send , msg , args ) : if not args [ 'config' ] [ 'feature' ] . getboolean ( 'hooks' ) : send ( "Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s)." ) return if args [ 'type' ] == 'privmsg' : send ( "Note-passing should be done in public." ) return try : nick , note = msg . split ( maxsplit = 1 ) nicks = set ( x for x in nick . split ( ',' ) if x ) except ValueError : send ( "Not enough arguments." ) return nickregex = args [ 'config' ] [ 'core' ] [ 'nickregex' ] + '+$' successful_nicks = [ ] failed_nicks = [ ] for nick in nicks : if re . match ( nickregex , nick ) : row = Notes ( note = note , submitter = args [ 'nick' ] , nick = nick , time = datetime . now ( ) ) args [ 'db' ] . add ( row ) successful_nicks . append ( nick ) else : failed_nicks . append ( nick ) if successful_nicks : send ( "Note left for %s." % ", " . join ( successful_nicks ) ) if failed_nicks : send ( "Invalid nick(s): %s." % ", " . join ( failed_nicks ) ) | Leaves a note for a user or users . |
14,921 | def from_frame ( klass , frame , connection ) : event = frame . headers [ 'new' ] data = json . loads ( frame . body ) info = data [ 'info' ] build = Build . fromDict ( info ) build . connection = connection return klass ( build , event ) | Create a new BuildStateChange event from a Stompest Frame . |
14,922 | def from_frame ( klass , frame , connection ) : event = frame . headers [ 'new' ] data = json . loads ( frame . body ) info = data [ 'info' ] task = Task . fromDict ( info ) task . connection = connection return klass ( task , event ) | Create a new TaskStateChange event from a Stompest Frame . |
14,923 | def cmd ( send , msg , args ) : if not msg : send ( "Ping what?" ) return channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'nick' ] if "." not in msg and ":" not in msg : targets = set ( msg . split ( ) ) if len ( targets ) > 3 : send ( "Please specify three or fewer people to ping." ) return for target in targets : if not re . match ( args [ 'config' ] [ 'core' ] [ 'nickregex' ] , target ) : send ( "Invalid nick %s" % target ) else : args [ 'handler' ] . ping_map [ target ] = channel args [ 'handler' ] . connection . ctcp ( "PING" , target , " " . join ( str ( time ( ) ) . split ( '.' ) ) ) return try : answer = subprocess . check_output ( [ args [ 'name' ] , '-W' , '1' , '-c' , '1' , msg ] , stderr = subprocess . STDOUT ) answer = answer . decode ( ) . splitlines ( ) send ( answer [ 0 ] ) send ( answer [ 1 ] ) except subprocess . CalledProcessError as e : if e . returncode == 2 : send ( "ping: unknown host " + msg ) elif e . returncode == 1 : send ( e . output . decode ( ) . splitlines ( ) [ - 2 ] ) | Ping something . |
14,924 | def execution_duration ( self ) : duration = None if self . execution_start and self . execution_end : delta = self . execution_end - self . execution_start duration = delta . total_seconds ( ) return duration | Returns total BMDS execution time in seconds . |
14,925 | def get_exe_path ( cls ) : return os . path . abspath ( os . path . join ( ROOT , cls . bmds_version_dir , cls . exe + ".exe" ) ) | Return the full path to the executable . |
14,926 | def plot ( self ) : fig = self . dataset . plot ( ) ax = fig . gca ( ) ax . set_title ( "{}\n{}, {}" . format ( self . dataset . _get_dataset_name ( ) , self . name , self . get_bmr_text ( ) ) ) if self . has_successfully_executed : self . _set_x_range ( ax ) ax . plot ( self . _xs , self . get_ys ( self . _xs ) , label = self . name , ** plotting . LINE_FORMAT ) self . _add_bmr_lines ( ax ) else : self . _add_plot_failure ( ax ) ax . legend ( ** settings . LEGEND_OPTS ) return fig | After model execution print the dataset curve - fit BMD and BMDL . |
14,927 | def write_dfile ( self ) : f_in = self . tempfiles . get_tempfile ( prefix = "bmds-" , suffix = ".(d)" ) with open ( f_in , "w" ) as f : f . write ( self . as_dfile ( ) ) return f_in | Write the generated d_file to a temporary file . |
14,928 | def to_dict ( self , model_index ) : return dict ( name = self . name , model_index = model_index , model_name = self . model_name , model_version = self . version , has_output = self . output_created , dfile = self . as_dfile ( ) , execution_halted = self . execution_halted , stdout = self . stdout , stderr = self . stderr , outfile = getattr ( self , "outfile" , None ) , output = getattr ( self , "output" , None ) , logic_bin = getattr ( self , "logic_bin" , None ) , logic_notes = getattr ( self , "logic_notes" , None ) , recommended = getattr ( self , "recommended" , None ) , recommended_variable = getattr ( self , "recommended_variable" , None ) , ) | Return a summary of the model in a dictionary format for serialization . |
14,929 | def merge_config ( d1 , d2 ) : result = deepcopy ( d1 ) elements = deque ( ) elements . append ( ( result , d2 ) ) while elements : old , new = elements . popleft ( ) new = OrderedDict ( [ ( k . lower ( ) , ( k , v ) ) for k , v in new . items ( ) ] ) visited_keys = [ ] for k , old_value in old . items ( ) : klow = k . lower ( ) if klow in new : new_key , new_value = new [ klow ] visited_keys . append ( new_key ) if all ( isinstance ( e , MutableMapping ) for e in ( old_value , new_value ) ) : elements . append ( ( old_value , new_value ) ) else : old [ k ] = deepcopy ( new_value ) for k , v in new . values ( ) : if k not in visited_keys : old [ k ] = deepcopy ( v ) return result | Merges to config dicts . Key values are case insensitive for merging but the value of d1 is remembered . |
14,930 | def set_if_none ( user_config , config , key , value ) : keys = key . split ( '.' ) for k in keys [ : - 1 ] : try : user_config = user_config [ k ] except KeyError : user_config = { } config = config [ k ] key = keys [ - 1 ] if key not in user_config and not config [ key ] : config [ key ] = value | If the value of the key in is None and doesn t exist on the user config set it to a different value |
14,931 | def set_admin ( msg , handler ) : if handler . config [ 'feature' ] [ 'servicestype' ] == "ircservices" : match = re . match ( "STATUS (.*) ([0-3])" , msg ) elif handler . config [ 'feature' ] [ 'servicestype' ] == "atheme" : match = re . match ( "(.*) ACC ([0-3])" , msg ) if match : status = int ( match . group ( 2 ) ) nick = match . group ( 1 ) if status != 3 : return with handler . db . session_scope ( ) as session : admin = session . query ( Permissions ) . filter ( Permissions . nick == nick ) . first ( ) if admin is None : session . add ( Permissions ( nick = nick , role = 'admin' , registered = True , time = datetime . now ( ) ) ) else : admin . registered = True admin . time = datetime . now ( ) | Handle admin verification responses from NickServ . |
14,932 | def is_tuple ( obj , len_ = None ) : if not isinstance ( obj , tuple ) : return False if len_ is None : return True if not isinstance ( len_ , Integral ) : raise TypeError ( "length must be a number (got %s instead)" % type ( len_ ) . __name__ ) if len_ < 0 : raise ValueError ( "length must be positive (got %s instead)" % len_ ) return len ( obj ) == len_ | Checks whether given object is a tuple . |
14,933 | def select ( indices , from_ , strict = False ) : ensure_iterable ( indices ) ensure_sequence ( from_ ) if strict : return from_ . __class__ ( from_ [ index ] for index in indices ) else : len_ = len ( from_ ) return from_ . __class__ ( from_ [ index ] for index in indices if 0 <= index < len_ ) | Selects a subsequence of given tuple including only specified indices . |
14,934 | def omit ( indices , from_ , strict = False ) : from taipan . collections . sets import remove_subset ensure_iterable ( indices ) ensure_sequence ( from_ ) if strict : remaining_indices = set ( xrange ( len ( from_ ) ) ) try : remove_subset ( remaining_indices , indices ) except KeyError as e : raise IndexError ( int ( str ( e ) ) ) else : remaining_indices = set ( xrange ( len ( from_ ) ) ) - set ( indices ) return from_ . __class__ ( from_ [ index ] for index in remaining_indices ) | Returns a subsequence from given tuple omitting specified indices . |
14,935 | def _describe_type ( arg ) : if isinstance ( arg , tuple ) : return "tuple of length %s" % len ( arg ) else : return type ( arg ) . __name__ | Describe given argument including length if it s a tuple . |
14,936 | def _create_image_url ( self , file_path , type_ , target_size ) : if self . image_config is None : logger . warning ( 'no image configuration available' ) return return '' . join ( [ self . image_config [ 'secure_base_url' ] , self . _image_size ( self . image_config , type_ , target_size ) , file_path , ] ) | The the closest available size for specified image type . |
14,937 | def from_json ( cls , json , image_config = None ) : cls . image_config = image_config return cls ( ** { attr : json . get ( attr if key is None else key ) for attr , key in cls . JSON_MAPPING . items ( ) } ) | Create a model instance |
14,938 | def _image_size ( image_config , type_ , target_size ) : return min ( image_config [ '{}_sizes' . format ( type_ ) ] , key = lambda size : ( abs ( target_size - int ( size [ 1 : ] ) ) if size . startswith ( 'w' ) or size . startswith ( 'h' ) else 999 ) , ) | Find the closest available size for specified image type . |
14,939 | def getallgroups ( arr , k = - 1 ) : if k < 0 : k = len ( arr ) return itertools . chain . from_iterable ( itertools . combinations ( set ( arr ) , j ) for j in range ( 1 , k + 1 ) ) | returns all the subset of |
14,940 | def open_get_line ( filename , limit = - 1 , ** kwargs ) : allowed_keys_for_get_line = { 'sep' , 'pw_filter' , 'errors' } for k in list ( kwargs . keys ( ) ) : if k not in allowed_keys_for_get_line : del kwargs [ k ] print ( "After filtering: {}" . format ( kwargs ) ) with open_ ( filename , 'rt' ) as f : for w , c in get_line ( f , limit , ** kwargs ) : yield w , c | Opens the password file named |
14,941 | def stop_workers ( self , clean ) : with executor_lock : self . executor . shutdown ( clean ) del self . executor with self . worker_lock : if clean : self . pool . close ( ) else : self . pool . terminate ( ) self . pool . join ( ) del self . pool for x in self . events . values ( ) : x . event . cancel ( ) self . events . clear ( ) | Stop workers and deferred events . |
14,942 | def extract_translations ( self , string ) : tree = ast . parse ( string ) visitor = TransVisitor ( self . tranz_functions , self . tranzchoice_functions ) visitor . visit ( tree ) return visitor . translations | Extract messages from Python string . |
14,943 | def cmd ( send , msg , args ) : if not msg : send ( "What are you trying to get to?" ) return nick = args [ 'nick' ] isup = get ( "http://isup.me/%s" % msg ) . text if "looks down from here" in isup : send ( "%s: %s is down" % ( nick , msg ) ) elif "like a site on the interwho" in isup : send ( "%s: %s is not a valid url" % ( nick , msg ) ) else : send ( "%s: %s is up" % ( nick , msg ) ) | Checks if a website is up . |
14,944 | def create_required_directories ( self ) : required = ( self . CACHE_DIR , self . LOG_DIR , self . OUTPUT_DIR , self . ENGINEER . JINJA_CACHE_DIR , ) for folder in required : ensure_exists ( folder , assume_dirs = True ) | Creates any directories required for Engineer to function if they don t already exist . |
14,945 | def cmd ( send , msg , args ) : if 'livedoc' in args [ 'name' ] : url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else : url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not msg : msg = get_rand ( url ) params = { 'format' : 'json' , 'action' : 'query' , 'list' : 'search' , 'srlimit' : '1' , 'srsearch' : msg } data = get ( '%s/api.php' % url , params = params ) . json ( ) try : article = data [ 'query' ] [ 'search' ] [ 0 ] [ 'title' ] except IndexError : send ( "%s isn't important enough to have a %s article." % ( msg , name ) ) return article = article . replace ( ' ' , '_' ) url += 'iki' send ( '%s/%s' % ( url , article ) ) | Returns the first wikipedia result for the argument . |
14,946 | def parse_devices ( self ) : devices = [ ] for device in self . _channel_dict [ "devices" ] : devices . append ( Device ( device , self . _is_sixteen_bit , self . _ignore_list ) ) return devices | Creates an array of Device objects from the channel |
14,947 | def update ( self ) : for device in self . devices : device . update ( ) for i in range ( len ( self . _channel_dict [ "devices" ] ) ) : device_dict = self . _channel_dict [ "devices" ] [ i ] for device in self . _devices : if device . name == device_dict [ "common.ALLTYPES_NAME" ] : self . _channel_dict [ "devices" ] [ i ] = device . as_dict ( ) | Updates the dictionary of the channel |
14,948 | def open_config ( self , type = "shared" ) : try : output = self . dev . rpc ( "<open-configuration><{0}/></open-configuration>" . format ( type ) ) except Exception as err : print err | Opens the configuration of the currently connected device |
14,949 | def close_config ( self ) : try : self . dev . rpc . close_configuration ( ) except Exception as err : print err | Closes the exiting opened configuration |
14,950 | def commit_config ( self ) : try : self . dev . rpc . commit_configuration ( ) except Exception as err : print err | Commits exiting configuration |
14,951 | def commit_and_quit ( self ) : try : self . dev . rpc . commit_configuration ( ) self . close_config ( ) except Exception as err : print err | Commits and closes the currently open configration . Saves a step by not needing to manually close the config . |
14,952 | def load_local_plugin ( name ) : try : module_name = '.' . join ( name . split ( '.' ) [ : - 1 ] ) module_obj = importlib . import_module ( name = module_name ) obj = getattr ( module_obj , name . split ( '.' ) [ - 1 ] ) return obj except ( ImportError , AttributeError , ValueError ) as e : raise PluginNotFoundError ( e ) | Import a local plugin accessible through Python path . |
14,953 | def load_installed_plugins ( ) : providers = { } checkers = { } for entry_point in pkg_resources . iter_entry_points ( group = 'archan' ) : obj = entry_point . load ( ) if issubclass ( obj , Provider ) : providers [ entry_point . name ] = obj elif issubclass ( obj , Checker ) : checkers [ entry_point . name ] = obj return collections . namedtuple ( 'Plugins' , 'providers checkers' ) ( providers = providers , checkers = checkers ) | Search and load every installed plugin through entry points . |
14,954 | def from_file ( path ) : with open ( path ) as stream : obj = yaml . safe_load ( stream ) Config . lint ( obj ) return Config ( config_dict = obj ) | Return a Config instance by reading a configuration file . |
14,955 | def find ( ) : names = ( 'archan.yml' , 'archan.yaml' , '.archan.yml' , '.archan.yaml' ) current_dir = os . getcwd ( ) configconfig_file = os . path . join ( current_dir , '.configconfig' ) default_config_dir = os . path . join ( current_dir , 'config' ) if os . path . isfile ( configconfig_file ) : logger . debug ( 'Reading %s to get config folder path' , configconfig_file ) with open ( configconfig_file ) as stream : config_dir = os . path . join ( current_dir , stream . read ( ) ) . strip ( ) elif os . path . isdir ( default_config_dir ) : config_dir = default_config_dir else : config_dir = current_dir logger . debug ( 'Config folder = %s' , config_dir ) for name in names : config_file = os . path . join ( config_dir , name ) logger . debug ( 'Searching for config file at %s' , config_file ) if os . path . isfile ( config_file ) : logger . debug ( 'Found %s' , config_file ) return config_file logger . debug ( 'No config file found' ) return None | Find the configuration file if any . |
14,956 | def inflate_nd_checker ( identifier , definition ) : if isinstance ( definition , bool ) : return Checker ( name = identifier , passes = definition ) elif isinstance ( definition , dict ) : return Checker ( definition . pop ( 'name' , identifier ) , ** definition ) else : raise ValueError ( '%s type is not supported for no-data checkers, ' 'use bool or dict' % type ( definition ) ) | Inflate a no - data checker from a basic definition . |
14,957 | def get_plugin ( self , identifier , cls = None ) : if ( ( cls is None or cls == 'provider' ) and identifier in self . available_providers ) : return self . available_providers [ identifier ] elif ( ( cls is None or cls == 'checker' ) and identifier in self . available_checkers ) : return self . available_checkers [ identifier ] return Config . load_local_plugin ( identifier ) | Return the plugin corresponding to the given identifier and type . |
14,958 | def provider_from_dict ( self , dct ) : provider_identifier = list ( dct . keys ( ) ) [ 0 ] provider_class = self . get_provider ( provider_identifier ) if provider_class : return provider_class ( ** dct [ provider_identifier ] ) return None | Return a provider instance from a dict object . |
14,959 | def checker_from_dict ( self , dct ) : checker_identifier = list ( dct . keys ( ) ) [ 0 ] checker_class = self . get_checker ( checker_identifier ) if checker_class : return checker_class ( ** dct [ checker_identifier ] ) return None | Return a checker instance from a dict object . |
14,960 | def inflate_plugin ( self , identifier , definition = None , cls = None ) : cls = self . get_plugin ( identifier , cls ) return cls ( ** definition or { } ) | Inflate a plugin thanks to it s identifier definition and class . |
14,961 | def inflate_analysis_group ( self , identifier , definition ) : providers_definition = definition . pop ( 'providers' , None ) checkers_definition = definition . pop ( 'checkers' , None ) analysis_group = AnalysisGroup ( ) try : first_plugin = self . inflate_plugin ( identifier , definition ) if isinstance ( first_plugin , Checker ) : analysis_group . checkers . append ( first_plugin ) if providers_definition is None : raise ValueError ( 'when declaring an analysis group with a checker ' 'identifier, you must also declare providers with ' 'the "providers" key.' ) analysis_group . providers . extend ( self . inflate_providers ( providers_definition ) ) elif isinstance ( first_plugin , Provider ) : analysis_group . providers . append ( first_plugin ) if checkers_definition is None : raise ValueError ( 'when declaring an analysis group with a provider ' 'identifier, you must also declare checkers with ' 'the "checkers" key.' ) analysis_group . checkers . extend ( self . inflate_checkers ( checkers_definition ) ) except PluginNotFoundError as e : logger . warning ( 'Could not find any plugin identified by %s, ' 'considering entry as group name. Exception: %s.' , identifier , e ) analysis_group . name = definition . pop ( 'name' , identifier ) analysis_group . description = definition . pop ( 'description' , None ) if bool ( providers_definition ) != bool ( checkers_definition ) : raise ValueError ( 'when declaring an analysis group with a name, you must ' 'either declare both "providers" and "checkers" or none.' ) if providers_definition and checkers_definition : analysis_group . providers . extend ( self . inflate_providers ( providers_definition ) ) analysis_group . checkers . extend ( self . inflate_checkers ( checkers_definition ) ) self . cleanup_definition ( definition ) for nd_identifier , nd_definition in definition . items ( ) : analysis_group . checkers . append ( self . inflate_nd_checker ( nd_identifier , nd_definition ) ) return analysis_group | Inflate a whole analysis group . |
14,962 | def print_plugins ( self ) : width = console_width ( ) line = Style . BRIGHT + '=' * width + '\n' middle = int ( width / 2 ) if self . available_providers : print ( line + ' ' * middle + 'PROVIDERS' ) for provider in sorted ( self . available_providers . values ( ) , key = lambda x : x . identifier ) : provider ( ) . print ( ) print ( ) if self . available_checkers : print ( line + ' ' * middle + 'CHECKERS' ) for checker in sorted ( self . available_checkers . values ( ) , key = lambda x : x . identifier ) : checker ( ) . print ( ) print ( ) | Print the available plugins . |
14,963 | def cmd ( send , msg , args ) : match = re . match ( r'--(.+?)\b' , msg ) randtype = 'hex' if match : if match . group ( 1 ) == 'int' : randtype = 'int' else : send ( "Invalid Flag." ) return if randtype == 'hex' : send ( hex ( getrandbits ( 50 ) ) ) else : maxlen = 1000000000 msg = msg . split ( ) if len ( msg ) == 2 : if msg [ 1 ] . isdigit ( ) : maxlen = int ( msg [ 1 ] ) else : send ( "Invalid Length" ) return send ( str ( randrange ( maxlen ) ) ) | For when you don t have enough randomness in your life . |
14,964 | def split ( X , Y , question ) : true_X , false_X = [ ] , [ ] true_Y , false_Y = [ ] , [ ] for x , y in zip ( X , Y ) : if question . match ( x ) : true_X . append ( x ) true_Y . append ( y ) else : false_X . append ( x ) false_Y . append ( y ) return ( np . array ( true_X ) , np . array ( false_X ) , np . array ( true_Y ) , np . array ( false_Y ) ) | Partitions a dataset . |
14,965 | def build_tree ( X , y , criterion , max_depth , current_depth = 1 ) : if max_depth >= 0 and current_depth >= max_depth : return Leaf ( y ) gain , question = find_best_question ( X , y , criterion ) if gain == 0 : return Leaf ( y ) true_X , false_X , true_y , false_y = split ( X , y , question ) true_branch = build_tree ( true_X , true_y , criterion , max_depth , current_depth = current_depth + 1 ) false_branch = build_tree ( false_X , false_y , criterion , max_depth , current_depth = current_depth + 1 ) return Node ( question = question , true_branch = true_branch , false_branch = false_branch ) | Builds the decision tree . |
14,966 | def print_tree ( root , space = ' ' ) : if isinstance ( root , Leaf ) : print ( space + "Prediction: " + str ( root . most_frequent ) ) return print ( space + str ( root . question ) ) print ( space + " ) print_tree ( root . true_branch , space + ' ' ) print ( space + " ) print_tree ( root . false_branch , space + ' ' ) | Prints the Decision Tree in a pretty way . |
14,967 | def find_element ( driver , elem_path , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : wait = WebDriverWait ( driver , timeout , poll_frequency ) return wait . until ( EC . presence_of_element_located ( ( by , elem_path ) ) ) | Find and return an element once located |
14,968 | def find_elements ( driver , elem_path , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : wait = WebDriverWait ( driver , timeout , poll_frequency ) return wait . until ( EC . presence_of_all_elements_located ( ( by , elem_path ) ) ) | Find and return all elements once located |
14,969 | def find_write ( driver , elem_path , write_str , clear_first = True , send_enter = False , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : elem = find_element ( driver , elem_path = elem_path , by = by , timeout = timeout , poll_frequency = poll_frequency ) if clear_first : elem . clear ( ) elem . send_keys ( write_str ) if send_enter : elem . send_keys ( Keys . ENTER ) return elem | Find a writable element and write to it |
14,970 | def cmd ( send , msg , args ) : if not msg : msg = gen_word ( ) send ( gen_intensify ( msg ) ) | Intensifies text . |
14,971 | def fetch_states ( self , elections ) : states = [ ] for election in elections : if election . division . level . name == DivisionLevel . DISTRICT : division = election . division . parent else : division = election . division states . append ( division ) return sorted ( list ( set ( states ) ) , key = lambda s : s . label ) | Returns the unique divisions for all elections on an election day . |
14,972 | def get_name ( self , type_ , id_ ) : cachefile = self . filename ( type_ , id_ ) try : with open ( cachefile , 'r' ) as f : return f . read ( ) except ( OSError , IOError ) as e : if e . errno != errno . ENOENT : raise | Read a cached name if available . |
14,973 | def put_name ( self , type_ , id_ , name ) : cachefile = self . filename ( type_ , id_ ) dirname = os . path . dirname ( cachefile ) try : os . makedirs ( dirname ) except OSError as e : if e . errno != errno . EEXIST : raise with open ( cachefile , 'w' ) as f : f . write ( name ) | Write a cached name to disk . |
14,974 | def get_or_load_name ( self , type_ , id_ , method ) : name = self . get_name ( type_ , id_ ) if name is not None : defer . returnValue ( name ) instance = yield method ( id_ ) if instance is None : defer . returnValue ( None ) self . put_name ( type_ , id_ , instance . name ) defer . returnValue ( instance . name ) | read - through cache for a type of object s name . |
14,975 | def call ( self , name , * args , ** kwargs ) : if name in ( 'getTaskInfo' , 'getTaskDescendants' ) : kwargs [ 'request' ] = True if kwargs : kwargs [ '__starstar' ] = True args = args + ( kwargs , ) payload = { 'methodName' : name , 'params' : args } self . calls . append ( payload ) | Add a new call to the list that we will submit to the server . |
14,976 | def _multicall_callback ( self , values , calls ) : result = KojiMultiCallIterator ( values ) result . connection = self . connection result . calls = calls return result | Fires when we get information back from the XML - RPC server . |
14,977 | def time_ago ( dt ) : now = datetime . datetime . now ( ) return humanize . naturaltime ( now - dt ) | Return the current time ago |
14,978 | def cmd ( send , msg , args ) : if not msg : user = choice ( get_users ( args ) ) else : user = msg send ( gen_insult ( user ) ) | Insults a user . |
14,979 | def needed ( name , required ) : return [ relative_field ( r , name ) if r and startswith_field ( r , name ) else None for r in required ] | RETURN SUBSET IF name IN REQUIRED |
14,980 | def _match_data_to_parameter ( cls , data ) : in_value = data [ "in" ] for cls in [ QueryParameter , HeaderParameter , FormDataParameter , PathParameter , BodyParameter ] : if in_value == cls . IN : return cls return None | find the appropriate parameter for a parameter field |
14,981 | def cmd ( send , msg , args ) : if not msg : result = subprocess . run ( [ 'eix' , '-c' ] , env = { 'EIX_LIMIT' : '0' , 'HOME' : os . environ [ 'HOME' ] } , stdout = subprocess . PIPE , universal_newlines = True ) if result . returncode : send ( "eix what?" ) return send ( choice ( result . stdout . splitlines ( ) ) ) return args = [ 'eix' , '-c' ] + msg . split ( ) result = subprocess . run ( args , stdout = subprocess . PIPE , stderr = subprocess . STDOUT , universal_newlines = True ) if result . returncode : send ( "%s isn't important enough for Gentoo." % msg ) else : send ( result . stdout . splitlines ( ) [ 0 ] . strip ( ) ) | Runs eix with the given arguments . |
14,982 | def to_str ( number ) : states = globals ( ) for name , value in states . items ( ) : if number == value and name . isalpha ( ) and name . isupper ( ) : return name return '(unknown state %d)' % number | Convert a task state ID number to a string . |
14,983 | def to_json ( self , filename , indent = 2 ) : d = self . to_dicts ( ) if hasattr ( filename , "write" ) : json . dump ( d , filename , indent = indent ) elif isinstance ( filename , string_types ) : with open ( os . path . expanduser ( filename ) , "w" ) as f : json . dump ( d , f , indent = indent ) else : raise ValueError ( "Unknown filename or file-object" ) | Return a JSON string of all model inputs and outputs . |
14,984 | def to_df ( self , recommended_only = False , include_io = True ) : od = BMDS . _df_ordered_dict ( include_io ) [ session . _add_to_to_ordered_dict ( od , i , recommended_only ) for i , session in enumerate ( self ) ] return pd . DataFrame ( od ) | Return a pandas DataFrame for each model and dataset . |
14,985 | def to_csv ( self , filename , delimiter = "," , recommended_only = False , include_io = True ) : df = self . to_df ( recommended_only , include_io ) df . to_csv ( filename , index = False , sep = delimiter ) | Return a CSV for each model and dataset . |
14,986 | def to_excel ( self , filename , recommended_only = False , include_io = True ) : df = self . to_df ( recommended_only , include_io ) if isinstance ( filename , string_types ) : filename = os . path . expanduser ( filename ) df . to_excel ( filename , index = False ) | Return an Excel file for each model and dataset . |
14,987 | def to_docx ( self , filename = None , input_dataset = True , summary_table = True , recommendation_details = True , recommended_model = True , all_models = False , ) : rep = Reporter ( ) for model in self : rep . add_session ( model , input_dataset , summary_table , recommendation_details , recommended_model , all_models , ) if filename : rep . save ( filename ) return rep | Write batch sessions to a Word file . |
14,988 | def save_plots ( self , directory , format = "png" , recommended_only = False ) : for i , session in enumerate ( self ) : session . save_plots ( directory , prefix = str ( i ) , format = format , recommended_only = recommended_only ) | Save images of dose - response curve - fits for each model . |
14,989 | def load_messages ( self , directory , catalogue ) : if not os . path . isdir ( directory ) : raise ValueError ( "{0} is not a directory" . format ( directory ) ) for format , loader in list ( self . loaders . items ( ) ) : extension = "{0}.{1}" . format ( catalogue . locale , format ) files = find_files ( directory , "*.{0}" . format ( extension ) ) for file in files : domain = file . split ( "/" ) [ - 1 ] [ : - 1 * len ( extension ) - 1 ] catalogue . add_catalogue ( loader . load ( file , catalogue . locale , domain ) ) | Loads translation found in a directory . |
14,990 | def disable_backup ( self ) : for dumper in list ( self . dumpers . values ( ) ) : dumper . set_backup ( False ) | Disables dumper backup . |
14,991 | def write_translations ( self , catalogue , format , options = { } ) : if format not in self . dumpers : raise ValueError ( 'There is no dumper associated with format "{0}"' . format ( format ) ) dumper = self . dumpers [ format ] if "path" in options and not os . path . isdir ( options [ 'path' ] ) : os . mkdir ( options [ 'path' ] ) dumper . dump ( catalogue , options ) | Writes translation from the catalogue according to the selected format . |
14,992 | def main ( ) : s = rawdata . content . DataFiles ( ) all_ingredients = list ( s . get_collist_by_name ( data_files [ 1 ] [ 'file' ] , data_files [ 1 ] [ 'col' ] ) [ 0 ] ) best_ingred , worst_ingred = find_best_ingredients ( all_ingredients , dinner_guests ) print ( 'best ingred = ' , best_ingred ) print ( 'worst ingred = ' , worst_ingred ) for have in ingredients_on_hand : if have in best_ingred : print ( 'Use this = ' , have ) | script to find a list of recipes for a group of people with specific likes and dislikes . Output of script |
14,993 | def batch ( iterable , n , fillvalue = None ) : ensure_iterable ( iterable ) if not isinstance ( n , Integral ) : raise TypeError ( "invalid number of elements in a batch" ) if not ( n > 0 ) : raise ValueError ( "number of elements in a batch must be positive" ) if fillvalue is None : fillvalue = object ( ) trimmer = lambda item : tuple ( x for x in item if x is not fillvalue ) else : trimmer = identity ( ) args = [ iter ( iterable ) ] * n zipped = izip_longest ( * args , fillvalue = fillvalue ) return imap ( trimmer , zipped ) | Batches the elements of given iterable . |
14,994 | def intertwine ( * iterables ) : iterables = tuple ( imap ( ensure_iterable , iterables ) ) empty = object ( ) return ( item for iterable in izip_longest ( * iterables , fillvalue = empty ) for item in iterable if item is not empty ) | Constructs an iterable which intertwines given iterables . |
14,995 | def iterate ( iterator , n = None ) : ensure_iterable ( iterator ) if n is None : deque ( iterator , maxlen = 0 ) else : next ( islice ( iterator , n , n ) , None ) | Efficiently advances the iterator N times ; by default goes to its end . |
14,996 | def unique ( iterable , key = None ) : ensure_iterable ( iterable ) key = hash if key is None else ensure_callable ( key ) def generator ( ) : seen = set ( ) for elem in iterable : k = key ( elem ) if k not in seen : seen . add ( k ) yield elem return generator ( ) | Removes duplicates from given iterable using given key as criterion . |
14,997 | def breadth_first ( start , expand ) : ensure_callable ( expand ) def generator ( ) : queue = deque ( [ start ] ) while queue : node = queue . popleft ( ) yield node queue . extend ( expand ( node ) ) return generator ( ) | Performs a breadth - first search of a graph - like structure . |
14,998 | def depth_first ( start , descend ) : ensure_callable ( descend ) def generator ( ) : stack = [ start ] while stack : node = stack . pop ( ) yield node stack . extend ( descend ( node ) ) return generator ( ) | Performs a depth - first search of a graph - like structure . |
14,999 | def regex ( regex ) : if not hasattr ( regex , 'pattern' ) : regex = re . compile ( regex ) pattern = regex . pattern flags = regex . flags codes = sre . parse ( pattern ) return _strategy ( codes , Context ( flags = flags ) ) . filter ( regex . match ) | Return strategy that generates strings that match given regex . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.